This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Tuesday, February 28, 2023

In what circumstances we need to use Exception Handling Mechanism. Discuss with example.

 Exception Handling Mechanism is used to handle the exceptional conditions that can arise during the execution of a program. These exceptional conditions can be runtime errors like division by zero, out of memory, etc. or user-defined errors like invalid input. The main purpose of using exception handling is to provide a way to gracefully handle these errors instead of crashing the program.

Let's consider an example where we need to use exception handling. Suppose we have a program that asks the user to enter two numbers and then divides the first number by the second number. If the second number is zero, the program will encounter a runtime error of division by zero. Instead of crashing the program, we can use exception handling to gracefully handle this error.

#include <iostream>
using namespace std;
int main() {
   int num1, num2, result;
   cout << "Enter two numbers: ";
   cin >> num1 >> num2;
   try {
      if (num2 == 0)
         throw "Divide by zero exception";
      result = num1 / num2;
      cout << "Result = " << result << endl;
   }
   catch(const char* msg) {
      cerr << msg << endl;
   }
   return 0;
}

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget