Skip to main content

Posts

Showing posts with the label Exception

What is Exception? How can we handle the exception? Explain with an example.

 In C++, an exception is an error that occurs during the execution of a program. When an exception occurs, it causes the program to terminate abruptly and can lead to unpredictable behavior. To handle exceptions, C++ provides a mechanism called exception handling. Exception handling allows us to catch and handle exceptions in a controlled manner, so that the program can continue executing without crashing. Here is an example that demonstrates how to handle exceptions in C++: #include <iostream> using namespace std; int main() {   int a = 10, b = 0, c;   try {     if (b == 0) {       throw "Division by zero!";     }     c = a / b;     cout << "Result: " << c << endl;   }    catch (const char* msg) {     cerr << "Error: " << msg << endl;   }   return 0; } In this example, we are trying to divide an integer 'a' by 'b'. If 'b' is zero, it will th...