Exception Handling
Learners Support Publications [Link]
Introduction
• Exceptions are errors or some peculiar problems
other than logic or syntax errors.
• Exceptions are runtime anomalies or unusual
conditions that a program may encounter while
executing.
Learners Support Publications [Link]
Introduction
• Anomalies includes :
– Division by zero
– Access to an array outside of its bounds
– Running out of memory or disk space
Learners Support Publications [Link]
Basics of Exception Handling
• The purpose of exception handling mechanism is
to provide means to detect and report an
exceptional circumstances so that appropriate
action can be taken.
• Exceptions are of two types:
– Synchronous Exception
• Out-of-range index
• Over-flow
– Asynchronous Exception
• Keyboard interrupts
Learners Support Publications [Link]
Basics of Exception Handling
• The mechanism has error handling code that
perform the following tasks:
– Find the problem ( Hit the exception )
– Inform that an error has occurred ( Throw the
exception )
– Receive the error information ( Catch the exception )
– Take corrective actions ( Handle the exception )
Learners Support Publications [Link]
Exception Handling Mechanism
• C++ exception handling mechanism is basically built upon threeckeywords,
namely, try. throw, and catch. The keyword try is used tocpreface a block of
statements (surrounded by braces] which may generate exceptions.
• This block of statements is known as try block. When an exception is detected, it
is thrown using a 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 of these two blocks are as follows:
Learners Support Publications [Link]
• …......
• …......
• try
• {
• ….......
• throw exception; // Block of statements which
• …....... // detects and throws an exception
• ….......
• }
• catch(type arg) // Catches exception
• {
• …........ //Block of statements that
• …........ // handles the exception
• …........
• }
• …........
• …........
Learners Support Publications [Link]
• When the try block throws an exception, the program control leaves the try
block and enters the catch statement of the catch block. Note that exceptions are
objects used to transmit information about a problem.
• If the type of object thrown matches the arg type in the catch statement, then
catch block is executed for handling the exception.
• If they do not match, the program is aborted with the help of the abort() function
which is invoked by default.
• When no exception is detected and thrown, the control goes to the statement
immediately after the catch block. That is, the catch block is skipped.
Learners Support Publications [Link]
#include <iostream> catch(int i) // Catches the exception
using namespace std; {
int main() cout « "Exception caught: x « " « x « "\n";
{ }
int a,b; cout « "END";
cout « "Enter Values of a and b \n"; return 0;
cin » a; }
cin » b; The output of Program 13.1:
int x = a-b; First Run
try Enter Values of a and b
{ 20 16
if(x != 0) Result (a/x) = 4
{ END
cout « "Result(a/x) = “ « a/x «“\n”; Second Run
} Enter Values of a and b
else // There's an exception 10 10
{ Exception caught: x = 0
throw(x); // Throws int object END
}
}
Learners Support Publications [Link]
• Function invoked by try block throwing exception
Learners Support Publications [Link]
The general format of code for this kind of catch(type arg) // Catches exception
relationship is shown below: {
type function(arg list) // Function with ….........
exception …......... Handles exception here
{ ….........
…....... }
…....... …...........
throw(object); // Throws exception
….......
….......
}
….........
….........
try
{
….......
…....... invoke function here
….......
}
Learners Support Publications [Link]
/ Throw point outside the try block int main()
#include <iostream> {
using namespace std; try
void divide(int x, int y, int z) {
{ cout « "We are inside the try block \n";
cout « "\nWe are inside the function \n"; divide(10,20,30); // Invoke divide()
if((x-y) != 0) // It Is OK divided(10, 10,20); // Invoke dlvide()
{ }
int R = z/(x-y); catch(int i) // Catches the exception
cout « "Result = " « R « "\n”; {
} cout « “Caught the exception \n";
else // There is a problem }
{ return 0;
throw(x-y); // Throw point }
}
}
Learners Support Publications [Link]
• The output of the Program 13.2:
We are inside the try block
• We are inside the function
• Result = -3
•
• We are inside the function
Caught the exception
Learners Support Publications [Link]
Throwing Mechanism
• When an exception that is desired to be handled is detected, it is thrown using
the throw statement in one of the following forms:
• throw(exception);
• throw exception;
• throw; // used for rethrowing an exception
•
• The operand object exception may be of any type, including constants. It is also
possible to throw objects not intended for error handling.
• When an exception is thrown, it will be caught by the catch statement associated
with the try block. That is, the control exits the current try block, and is
transferred to the catch block after that try block.
• Throw point can be in a deeply nested scope within a try block or in a deeply
nested function call. In any case, control is transferred to the catch statement
Learners Support Publications [Link]
Catching Mechanism
• As stated earlier, code for handling exceptions is included in catch blocks. A catch block
looks like a function definition and is of the form
• catch(type arg)
• // Statements for
• // managing exceptions
}
• The type indicates the type of exception that catch block handles. The parameter arg is
an optional parameter name. Note that the exception-handling code is placed between
two braces. The catch statement catches an exception whose type matches with the type
of catch argument. When it is caught, the code in the catch block is executed.
• If the parameter in the catch statement is named, then the parameter can be used in the
exception-handling code. After executing the handler, the control goes to the statement
immediately following the catch block.
• Due to mismatch, if an exception is not caught, abnormal program termination will
occur. It is important to note that the catch block is simply skipped if the catch statement
does not catch an exception.
Learners Support Publications [Link]
Multiple Catch Statements
• It is possible that a program segment has more than one condition to throw an exception. In such
cases, we can associate more than one catch statement with a try (much like the conditions in a
switch statement) as shown below:
• try
• {
• // try block
• }
• catch(type1 arg)
• {
• // catch block1
• }
• catch(type2 arg)
• {
• // catch block2
• }
• catch(typeN arg)
• {
• // catch blockN
Learners Support Publications [Link]
• }
• When an exception is thrown, the exception handlers are searched in order for an
appropriate match. The first handler that yields a match is executed.
• After executing the handler, the control goes to the first statement after the last catch
block for that try. (In other words, all other handlers are bypassed). When no match is
found, the program is terminated.
• It is possible that arguments of several catch statements match the type of an exception.
In such cases, the first handler that matches the exception type is executed
Learners Support Publications [Link]
{
#include <iostrearn> cout« "Caught an integer \n";
using namespace std; }
void test(int x) catch(double d) // Catch3
{ {
try cout< <"Caught a double\n";
{ }
if(x==1) throw x; int cout<< "End of try-catch system \n\n";
else }
If (x==0) throw 'x'; // char int main()
else {
if(x==-1) throw1.0; // double cout< <"Testing Multiple Catches\n";
cout<< "End of try-block\n"; cout< <"x==1\n";
} test(1);
catch(char c) // Catch1 Cout<< "x==0 \n";
{ test(0);
Cout << "Caught a character \n"; cout<< "x==-1\n";
test(-1);
} cout<< "x==2\n";
catch(int m) // Catch 2 test(2);
Learners Support Publications [Link] return0;
#include <iostream>
void test(int x)
{
try
{
if(x==0)throw x; // int
if(x== -1)throw 'x'; //char
if(x==1)throw 1.0; // float
}
catch(...) // catch all
{
cout<< "Caught an exception\n";
int main()
{
cout << "Testing Generic Catch \n";
test(-1);
test(0);
test(1);
return0;
}
Learners Support Publications [Link]
Rethrowing an Exception
• A handler may decide to rethrow the exception caught without processing
• it. In such situations, we may simply invoke throw without any arguments
• as shown below:
• throw;
• This causes 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.
Learners Support Publications [Link]
#include <iostream> int main()
using namespace std; {
void divide(double x, double y) cout « "Inside main \n";
{
cout « "Inside function \n";
try
try {
{ divide(10.5,2.0);
if(y == 0.0) divide(20.0,0.0);
throw y; // Throwing double }
else
cout « “Division = " « x/y « “\n”;
catch(double)
} {
catch(double) // Catch a double cout « "Caught double inside main
{ \n”;
cout « "Caught double Inside function }
\n";
throw; // Rethrowing double
cout « “End of main \n”;
} return 0;
cout « "End of function \n\n"; }
}
Learners Support Publications [Link]
• The output of the Program 13.5:
• Inside main
• Inside function
• Division = 5.25
• End of function
• Inside function
• Caught double inside function
• Caught double Inside main
• End of main
• When an exception is rethrown, it will not be caught by the same catch
statement or any other catch in that group. Rather, it will be caught by an
appropriate catch in the outer try/catch sequence only.
• A catch handler itself may detect and throw an exception. Here again, the
exception thrown will not be caught by any catch statements in that group. It
will be passed on to the next outer try/catch sequence for processing.
Learners Support Publications [Link]
• Specifying Exceptions
• It is possible to restrict a function to throw only certain specified exceptions.
This is achieved by adding a throw list clause to the function definition. The
general form of using an exception specification is:
• type function(arg-list) throw (type-list)
• {
• ….......
• …....... Function body
• ….......
• }
Learners Support Publications [Link]
• The type-list specified of exceptions yhat may be [Link] any other
type of exception will cause abnormal program [Link] we wish to
prevent a function from throwing any exception, we may do so by making the
[Link] is,we must use
• throw();
• In the function header line.
Learners Support Publications [Link]
#include <iostream> catch(double d) // Catch3
void test(int x)throw(int,double) {
{ cout< <"Caught a double\n";
try }
{ cout<< "End of try-catch system \n\n";
if(x==0)throw x; // char }
else int main()
if(x== 1)throw 'x'; //int {
else cout< <"Testing Multiple Catches\n";
if(x==-1)throw 1.0; // double cout< <"x==1\n";
Cout<<“End of function block \n” test(1);
} Cout<< "x==0 \n";
catch(char c) // Catch1 test(0);
{ cout<< "x==-1\n";
Cout << "Caught a character \n"; test(-1);
} cout<< "x==2\n";
catch(int m) // Catch 2 test(2);
{ return0;
cout« "Caught an integer \n"; }
} Output
Testing Throw Restriction
X==0 caught a character
Learners Support Publications [Link] End of try-catch system
Thank You
Learners Support Publications [Link]