Exception handling in Object Oriented Language
Exception Handling is a common concept in object oriented programming languages like C++, Java and C#. Exceptions occur when a program executes abnormally due to conditions outside the program’s control, such as low memory or I/O errors.
The order in which catch handlers appear is significant, because handlers for a given try block are examined in order of their appearance.
After a matching catch handler is found, subsequent handlers are not examined. As a result, an ellipsis (…) catch handler must be the last handler for its try block.
The following is the syntax for exception handling in C++:
try
// code that may generate exceptions
( throw exceptions)
} catch( type1 id1) {
//handle exceptions of type1
} catch(type2 id2) {
//handle exceptions of type2
}{
Some sample C++ code snippets to illustrate exception handling:
class Inner {
public:
Inner();
~Inner();
void fun();
};
class Outer {
public:
Outer();
~Outer();
void fun();
};
Inner::Inner()
{
cout << "Inner constructor\n";
}
Inner::~Inner()
{
cout << "Inner destructor\n";
}
void Inner::fun()
{
cout << "Inner fun\n";
throw 1; //throw an exception
cout << "This statement is not executed\n";
}
Outer::Outer()
{
cout << "Outer constructor\n";
}
Outer::~Outer()
{
cout << "Outer destructor\n";
}
void Outer::fun()
{
Inner in;
cout << "Outer fun\n";
in.fun();
}
int main()
{
Outer out;
try
{
out.fun();
cout << "\nThis line will also not be executed" << endl;
}
catch (int i) {
cout << "Exception " << i << " occurred" << endl;
}
catch (...) { //ellipsis handler, handle any type of exceptions
cout << ”Exception occurred" << endl;
}
return 0;
}
Generated output:
Outer constructor
Inner constructor
Outer fun
Inner fun
Inner destructor
Exception 1 occurred
Outer destructor