Exception Handling
Definition:
In C++,exceptions are runtime anomalies or abnormal conditions that a program encounters during its execution.The process of handling these exceptions is called exception handling. Using the exception handling mechanism, the control from one part of the program where the exception occurred can be transferred to another part of the code.
C++ Exception
An exception is an unexpected problem that arises during the execution of a program our program terminates suddenly with some errors/issues.Exception occurs during the running of the program (runtime).
C++ try and catch
- try:The try keyword represents a block of code that may throw an exception placed inside the try block. It’s followed by one or more catch blocks. If an exception occurs, try block throws that exception.
- catch:The catch statement represents a block of code that is executed when a particular exception is thrown from the try block. The code to handle the exception is written inside the catch block.
- throw:An exception in C++ can be thrown using the throw keyword. When a program encounters a throw statement, then it immediately terminates the current function and starts finding a matching catch block to handle the thrown exception.
Example:
// C++ program to demonstate the use of try,catch and throw // in exception handling. #include <iostream> #include <stdexcept> using namespace std; int main() { // try block try { int numerator = 10; int denominator = 0; int res; // check if denominator is 0 then throw runtime // error. if (denominator == 0) { throw runtime_error( "Division by zero not allowed!"); } // calculate result if no exception occurs res = numerator / denominator; //[printing result after division cout << "Result after division: " << res << endl; } // catch block to catch the thrown exception catch (const exception& e) { // print the exception cerr << "Exception " << e.what() << endl; } return 0; }
Output