Exception Handling in C++
Exception Handling in C++
LEARNING OBJECTIVES
ableto
will be
this chapter, you
through
After going exception
handling
D i s c u s s the
basics of
mechanism
handling
mustrate exception mechanisms
and rethrowing
Explain throwing, catching throw only specific
types of exceptions
restricted to fin
functions are and operator overloaded nctions
Explain how c o n s t r u c t o r s / d e s t r u c t o r s
in
Interpret the
use of exceptions
13.1 INTRODUCTION
an unusual
situation at runtime. Such
Sometimes programs may
encounter
are run time anomalist
errors. They are known as exceptions. Exceptions as
logical errors nor as syntax conditions such as
labelled as
encounter while executing. Anomalies might include COuniersa
unusual conditions that a program may When a program encdu
or disk space.
or running out of memory
array outside of its bounds,
zero, access to an ANSI C++ provides buil-in
by that it is identified and dealt with effectively.
exceptional condition, it is important
are basically run time errors.
features to detect and handle exceptions which almostal
to ANSI C * 10
C++. It is a new feature added
wilhdte
Exception handling was not part of the original
integrated approacn,
compilers support this feature. C++ exception handling provides type-safe,
a
Exceptions are of two kinds, namely, synchronous exceptions and asynchronous excePo caused exceptions.
posedexcepu
that are
range index" and "over-flow" belong to the synchronous type exceptions. The errors that
exceptions. The propo
errors
the control of the program (such as keyboard interrupts) are called asynchronous exCept
handling mechanism in C++ is designed to handle only synchronous exceptions.
375
Exception Handling
the
the
e x c e
dling mechanism is to
exception hand p t i c
aropriate acti
that appropriate action can be taken. The mechanism suggests
an
"exceptional
The
ewmstance" So
a
separate error handling code that
following tasks
erormsthefo
handling
code basically consists of two segments, one to detect errors and to throw
The
e r r o r
try block
3 EXCEPTION HANDLING MECHANISM
13.3
sa handling mechanism is basically built upon three keywords,
CHexceptionhandli Detects and throws
an exception
throw, and catch. The keyword try is used to preface a block
ely, try,
atements (surrounded by braces) which may generate exceptions. This
f satements is known as try block. When an exception is detected,
hrown using a throw statement in the try block. A catch block defined
Exception
s thro object
keyword catch 'catchees the exception 'thrown' by the throw
by the
ement in the try block, and handles it appropriately. The relationship is catch block
Stalen
sown in Fig. 13.1.
Catches and handles
The catch block that catches an exception must immediately follow the the exception
y block that throws the exception. The general form of these two blocks
as follows: Fig.13.1 The block throwing exception
try
then catch
block is they do
statement,
is invoked by default.When no ex
in the catch function which lion
thrown matches the arg type That is, the catck
the help of the abort) the catch block. ch block is
aborted with after
match, the program is immediately
not control goes to the statement
13.1.
is detected and thrown, the illustrated in Program
mechanism is
skipped. This simple try-catch
an Exception
Block Throwing
Program 13.1 Try
#include <iostream>
if (x != 0)
=" << a/x << "\n";
cout << "Result (a/x)
There is an exception
else //
return 0;
First Run
Second Run
Enter Values of a and b
10 10
377
ExceptionHandling
caught: DIVIDE BY ZERO
ion
BXception
END
Programdete
dotects and catches a division-by-zero problem. The output of first run shows a successful execution. When
catch block is skipped and execution resumes with
is thrown,
exception
the first line after the catch. In the second
comes zero and therefore a
denominator x becor
no
division-by-zero situation occurs. This exception is thrown using
aD theSince the exception obJect is an int type, the catch statement containing int type argument catches the
t h eo b j e c t
exception and displays ecessary message.
exceptions are thrown by functions that are invoked from within the try blocks. The point at which the
t often, is called the throw point. Once an exception is thrown to the catch block, control cannot return to the
Mostted
This kind of relationship is shown in Fig. 13.2.
throw
point,
throw
Throw point
Invoke
try block
function
catch block
(Contd.)
ore e d Programm
378
Object-Oriented Programming with C
try
//Catches excepti on
catch (type arg)
Function that
Generates Exception
Program 13.2 Invoking
cout "\nWe
<< are inside the function \n"
if ( (x-y) I= 0) / / It is OK
int R = z /(x-y);
cout << "Result = " << R << "\n";
int main ()
try
EXception Handling
return 0;
the function
We areinside
Caught the exception
throw (exception) ;
throw exception;
// used for rethrowing an exception
throw
The operand object exception may
be of any type, including constants. It is also possible to throw objects not intended
for error handling.
it will be caught by the catch statement associated with the try block. That is, the control
When an exception is thrown,
catch block after that try block.
exits the current try block, and is transferred to the
be in nested scope within a try block or in a deeply nested function call. In any case,
Throw point can a deeply
control is transferred to the catch statement.
// Statements for
managing excepti ons
380
Object-Oriented Programming with C
The type
indicates the type of excepeption that catch block handles. The parameter arg is
name. Note that s an optional
the
exception whose exception-handling code is placed between two braces. The catch
statemePara
type matches with the type of catch
argument. When it 1s Caugnt, the code in the neter
executed. che
catch blodk
If the
parameter
in the catch is named, then the parameter can be used in the
statement eption-handling coe
CACCuting 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 vwl occur It is
important
c Catch block is
simply skipped if the catch statement does not catch an exception. note th
try
// try block
/ / catch block1
// catch block2
// catch blockN
When an exception is thrown, the exception handlers are searched in order for an appropriate match. The finst
handler that yields a match is executed. After executing the handler, the control goes to the first statement after the lat
catch block for that try. (In other words, all other handlers are bypassed). When no match is found, the progam is
terminated.
It is possible that arguments of several catch statements match the type of an exception. In such cases, the fins
handler that matches the exception type is executed.
Program 13.3 shows a simple example where multiple catch statements are used to handle various typesofexceptians
301
381
Exception Handling
std;
using namespace
test
(int x)
void
try
1) throw x; 1/ int
if(x==
else
i f(x= 0) throw x ' ; // char
else
i f (x == -1) throw 1.0; /l double
cout << End of try-block \n"
m) // Catch 2
cat ch (int
cout << Caught an integer \n'"
int main ()
test (1)
cout << "x == 0 \n"
test (0)
cout << "x == -1 \n"
test (-1);
cout << "x == 2 \n";
test(2):
return 0;
X==-1
Caught a double
End of try-catch system
X = 2
End of try-block
End of try-catch system
with =
I and therefore throws X an int exception
first, invokes the function test)
x
The program when executed
executed. Immediately after the execu
This
therefore catch2 handler is
matches the type of the parameter m in catch2 and
throws X, a character type exception
the function test() is again invoked with x 0. This time, the function
=
and
the handler catch3 is executed when a double type exception is
rown. thro
therefore the first handler is executed. Finally,
which catches the exception is executed and all other handlers are bypassed
Note that every time the
only handler
catch (. . .)
#include <iostream>
try
(Contd)
383
Exception Handing
int m a i n 0
Caught an exception
Caught an exception
Caught an exception
Note Note that all the throws were caught by the catch(.) statement
It may be a good idea to use the catch(...) as a default statement along with other catch handlers so that it can catch
all those exceptions which are not handled explicitly.
Note Remember, catch(.).should always be placed last in the list of handlers. Placing it before other
catch blocks would prevent those blocks trom catching exceptions and will cause a syntax error
#include <iostream>
#include <cstring>
uS2ng namespace std
(Contd)
384
Object-Oriented Programming with Ct
class Error
int err_code;
char *err_desc;
public
Error (int c, char *d)
err_code=C;
err_desc=new char [strlen (d) ]
strcpy (err_desc, d) ;
int main ()
try
"
catch (Error e)
"
return 0;
throw
This causes the current exception to be thrown to the next enclosing try/catch sequence and is caught by a ca
atch
statement listed after that enclosing try block, Program 13.6 demonstrates how an exception is rethrown and caug
385
Exception Handling
13.6 Rethrowing an Exception
Program 13.6
include <iostreams
i f (y == 0.0)
throw Y: // Throwing double
else
cout << Division =
"
<< x/y << "\n";
int main ()
divide (10.5,2.0)
divide (20.0,0.0);
catch (double)
return 0;
Inside main
Inside function
Division = 5.25
End of function
Inside function
augnt double inside function
386
Oblact:Oriented Programming with G
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 ecatch in the
tch in that
it will be caught by an appropriate catch in the outer try/eatch sequence only. group. Rathe
A catch handler itself may detect and throw an exception. Here again, the exception thrown will not ho
be
catch statements in that group. It will be passed on to the next outer try/catch sequence for processing caught tby any
Function body
Program 13.7 demonstrates how we can restrict a function to throw only certain types and not all.
#include <iostream>
using namespace std;
void test (int x) throw (int, double)
i f(x == 0) throw 'x';
// char
else
if (x ==
1) throw x; 1/ int
else
(Contul)
387
Exception Handling
i f (x==-1) throw
cOut << Enod of 1.0; // double
function block \n"
int main ()
try
cout <<
Testing Throw Restrictions
cout << "x 0 \n";
==
\n"
test(0);
cout << "x 1
==
\n"
test(1));
cout <<
X-1 \n" ;
test (-1);
cout << "x 2
==
\n"
test (2)
catch (char c)
cout <<
"Caught a
character \n";
catch (int m)
cout <<
"Caught an
integer \n"
catch (double d)
cout <<
"Caught a double \n";
cout << End of
try- catch system \n\n";
return 0;
class A
public:
try
data-type d1;
//Constructor code
throw e
catch (e)
Now consider the case of destructors throwing exceptions. An exception raised during the execution of the
destructor block may also lead to the memory leak situation as the destructor might not have released all the
reserved memory space before the exception is raised. Though, it is possible to handle the exception raised by
the destructor inside the main block but at times it may lead to the program getting aborted. This may happen
Thus,
when the program control has already left the object's context before its raised exception could be handled.
it is advisable to handle the exception raised by the destructor with in the destructor block, as shown below:
class A
public
A)
389
Exception Handlin
-A()
tY
//Destructor code
throw
catch ( )
class complex
public
class FLAG{}; //Abstract class FLAG