|
|
Exception Handling / Error Handler in C++
|
Tutorials

Cpp

|
Topic |
What is Exception Handling in C++?
|
|
Explanation |
|
Exception Handling 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, throw and catch. 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.
| Throw point |
| Function that causes an exception. |
|
| try block |
| Invokes a function that contains an exception. |
|
| catch block |
| Catches and handles the exception. |
|
Example:
#include <iostream.h>
int main()
{
int x,y;
cout << "Enter values of x::";
cin >> x;
cout << "Enter values of y::";
cin >> y;
int r=x-y;
try
{
if ( r!=0)
{
cout << "Result of division is x/r:: " << x/r << "\n";
}
else
{
throw ( r);
}
}
catch( int r)
{
cout << "Division by zero exception::
value of r is::" << r << "\n";
}
cout << "END";
return 0;
}
|
Result:
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++.
|
| Note |
C++ is one of the most used programming languages in the world. Also known as "C with Classes".
Hope you enjoy this tutorial. Do send your feedback or suggestions on this C++ tutorial. This is a copyright content.
|
|
|
|