Exceptions are events that occur during the execution of a program that disrupt the normal flow of instructions (e.g. divide by zero, array access out of bound, etc.) and is based on 3 keywords: try, catch, and throw in c++.
Exception Handling Syntax
try {
// protected code
}
catch( ExceptionName e1 ) { // catch block }
catch( ExceptionName e2 ) { // catch block }
catch( ExceptionName eN ) { // catch block }
Keyword |
Details |
try Block |
Code which generates exceptions written in try block |
Catch Block |
It is used to catch exceptions which are there in the try block and program can consists of more than 1 catch block. |
throw |
Program throws an exception which is done using a throw keyword. |
Program |
Output |
#include
using namespace std;
double div(int a, int b) {
if( b == 0 ) { throw "Division by zero condition!"; }
return (a/b);
}
int main () {
int x = 50; int y = 0; double z = 0;
try { z = div(x, y);
cout << z << endl;
} catch (const char* msg) { cerr << msg << endl; }
return 0;
}
|
Division by zero condition!
|
Rethrowing an exception
Program |
Output |
#include
using namespace std;
void MyHandler()
{
try
{ throw “hello”; }
catch (const char*)
{
cout <<”Caught exception inside MyHandler\n”;
throw; //rethrow char* out of function
}
}
int main()
{ cout<< “Main start”;
try
{ MyHandler(); }
catch(const char*)
{
cout <<”Caught exception inside Main\n”;
}
cout << “Main end”;
return 0;
}
|
Main start
Caught exception inside MyHandler
Caught exception inside Main
Main end
|
|