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.

Wednesday, February 15, 2023

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 throw an exception with the message "Division by zero!" using the "throw" statement.

The 'try' block is used to enclose the code that may throw an exception. If an exception is thrown inside the 'try' block, the program execution jumps to the matching "catch" block.

The 'catch' block catches the exception and handles it. In this example, the 'catch' block catches the exception thrown by the "try" block and prints an error message to the standard error stream using the 'cerr' object.

In this way, we can handle exceptions and continue the program execution even if an exception occurs. It is important to note that exception handling should be used sparingly and only for exceptional circumstances, as it can have performance implications if overused.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget