Exception Handling / Error Handler in C++
What is Exception Handling in C++?
provides a mechanism to detect and report an exceptional circumstance, so that corrective action can be taken to set right the error occurred. Error Handler in C++ consists of three major keywords namely try
. The "try"
block is a set of code which generates an exception which is thrown using the "throw"
statement. The "catch"
block is used to catch the exception and handles it appropriately.
|Function that causes an exception. |
|Invokes a function that contains an exception.|
|catch block |
|Catches and handles the exception. |
#include <iostream.h> int main()
cout << "Enter values of x::";
cin >> x;
cout << "Enter values of y::";
cin >> y;
if ( r!=0)
cout << "Result of division is x/r:: " << x/r << "\n";
throw ( r);
catch( int r)
cout << "Division by zero exception::
value of r is::" << r << "\n";
cout << "END";
Enter values of x::12
Enter values of y::12
Division by zero exception::value of r is::0
In the above example, when the value "x" is divided by "0" an exception is thrown. Using the "catch" statement the exception is caught. This is the Error Handler System in C++.