HackerRank C++ Cpp exception handling




In this challenge, the task is to debug the existing code to successfully execute all provided test files.



  1. #include <iostream>
  2. #include <stdexcept>
  3. using namespace std;
  4. int largest_proper_divisor(int n) {
  5. if (n == 0) {
  6. throw invalid_argument("largest proper divisor is not defined for n=0");
  7. }
  8. if (n == 1) {
  9. throw invalid_argument("largest proper divisor is not defined for n=1");
  10. }
  11. for (int i = n/2; i >= 1; --i) {
  12. if (n % i == 0) {
  13. return i;
  14. }
  15. }
  16. return -1; // will never happen
  17. }
  18. void process_input(int n) {
  19. try {
  20. int d = largest_proper_divisor(n);
  21. cout << "result=" << d << endl;
  22. }
  23. catch(invalid_argument e){
  24. cout << e.what() << endl;
  25. }
  26. cout << "returning control flow to caller" << endl;
  27. }
  28. int main() {
  29. int n;
  30. cin >> n;
  31. process_input(n);
  32. return 0;
  33. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube