Cpp exception handling In C++ hackerrank solution

Problem statement:

You are given two integers, a and b. You need to calculate a/b.

If b is zero, you need to throw an exception and print "Exception: Division by zero!" Otherwise, you need to print the result of a/b.

      

Sample Input:

The input consists of two integers a and b, separated by a space.
10 3
      

Sample Output:

If b is zero, print "Exception: Division by zero!" Otherwise, print the result of a/b as a floating-point number, rounded to two decimal places.
3.33

Explanation:

In this example, a = 10 and b = 3. The result of a/b is 10/3 = 3.33333333333, rounded to two decimal places, which is 3.33.

      
  #include <iostream>
  #include <iomanip>
  #include <exception>
  using namespace std;
  
  class DivideByZeroException : public exception {
  public:
      const char* what() const throw() {
          return "Exception: Division by zero!";
      }
  };
  
  double division(int a, int b) {
      if (b == 0) {
          throw DivideByZeroException();
      }
      return static_cast(a) / b;
  }
  
  int main() {
      int a, b;
      cin >> a >> b;
  
      try {
          double result = division(a, b);
          cout << fixed << setprecision(2) << result << endl;
      } catch (const DivideByZeroException& e) {
          cout << e.what() << endl;
      }
  
      return 0;
  }
  

Code Explanation


We start by including the necessary header files, including for input/output operations, for setting precision, and for defining and handling exceptions.

We define a custom exception class DivideByZeroException that inherits from the base class exception. The what() function is overridden to return the error message "Exception: Division by zero!" when this exception is thrown.

The division function takes two integers a and b as input and performs the division a/b. If b is zero, it throws a DivideByZeroException exception.

In the main() function, we read the input values a and b using cin.

Inside a try-catch block, we call the division function with a and b.

If a DivideByZeroException exception is thrown, the catch block is executed, and the error message is printed using e.what().

If no exception is thrown, the result of the division is printed using cout, with fixed precision set to 2 decimal places.

Finally, we return 0 to indicate successful execution.

The solution demonstrates the usage of exception handling in C++, including the creation of a custom exception class and throwing/catching exceptions. It also handles the input based on the given format and provides the expected output.

I hope this solution meets your requirements and provides a clear understanding of the problem and its solution!