Module 5
Module 5
The error handling code mainly consist of two segments, one to detect error and throw
exceptions and other to catch the exceptions and to take appropriate actions.
Exception handling mechanism:-
C++ exception handling mechanism is basically built upon three keywords namely try,throw
and catch.
The keyword try is used to preface a block of statements which may generate
exceptions. This block of statement is called try block.
When an exception is detected it is thrown using throw statement in the try block.
A catch block defined by the keyword catch ‘catches’ the exception thrown by the
throw statement in the try block and handles it appropriately. The catch block that
catches an exception must immediately follow the try block that throws the exception.
The general form for this is
When the try block throws an exception, the program control leaves the try block and enters the
catch statement of the catch block. If the type of object thrown matches the arg type in the catch
statement, then the catch block is executed for handling the exception. If they do not match, the
program is aborted with the help of abort() function which is executed implicitly by the compiler.
When no exception is detected and thrown, the control goes to the statement immediately after the
catch block i.e catch block is skipped. The below diagram will show the mechanism of exception
handling
#include<iostream.h>
#include<conio.h>
void test(int x)
{
try
{
if (x > 0)
throw x;
else
throw 'x';
}
catch (int x)
{
cout << "Catch a integer and that integer is:" << x;
}
catch (char x)
{
cout << "Catch a character and that character is:" << x;
Rethrowing an Exception:-
A handler may decide to rethrow an exception caught without processing them.In such situations we
can simply invoke throw without any argument like
throw;
This cause the current exception to be thrown to the next enclosing try/catch sequence and is caught
by a catch statement listed after that enclosing try block. The following program shows how an
exception is rethrown and caught.
/* Example of 'rethrowing' an exception. */
#include<iostream>
using namespace std;
void sub(int i,int j)
{
try
{
if(i==0)
{
throw i;
}
else
cout<<“Subtraction result is: “<<i-j<<endl;
}
catch(int i)
{
cout<<“Exception caught inside sub()\n”;
throw;
}
};
int main()
{
try
{
sub(8,4);
sub(0,8);
}
catch(int k)
{
cout<<“Exception caught inside main()\n”;
}
Specifying Exceptions:-
In some cases it may be possible to restrict a function to throw only certain specified exceptions.
This is achieved by adding a throw list clause to function definition.
The general form of using an exception specification is:
Type function (arg-list) throw (type-list)
{
………….. …………
function body
……….
}
The type list specifies the type of exceptions that may be thrown.Throwing any other type of
exception will cause abnormal program termination.To prevent a function from throwing any
exception, it can be done by making the type list empty like