0% found this document useful (0 votes)
48 views16 pages

Exception Handling in C++

This document discusses exception handling in C++. It introduces exception handling, explains how exceptions are thrown and caught, and how exception handling works in functions, constructors, destructors and operator overloading. It also discusses the basics of exception handling in C++.

Uploaded by

Tanmoy Mitra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views16 pages

Exception Handling in C++

This document discusses exception handling in C++. It introduces exception handling, explains how exceptions are thrown and caught, and how exception handling works in functions, constructors, destructors and operator overloading. It also discusses the basics of exception handling in C++.

Uploaded by

Tanmoy Mitra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

1 3Exception Handling

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

might have bugs. The


two most common tm
time. It
that a program
works correctly the first of the problem at
We know that it is very O c c u r due to poor understanding
rare
errors
and syntactic errors. The logical can detect these emniy
of bugs are logical errors
understanding of the language itself. We
poor due to
solution procedure. The syntactic errors arise
exhaustive debugging and testing
procedures.
using unusual circumstance can neher t

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

unusual predictable problems that arise while executing a program.

13.2 BASICS OF EXCEPTION HANDLING


such as
Errorsb y eventsb e y o

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

provide means to detect and report


purpose
of

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

problem (Hit the exception).


the
Find errorhas o c c u r (Throw the exception).
hat
2 Ihformtha an
error information (Catch the exception).
3 Recerve
actions (Handle the exception).
rrective
4Take

handling
code basically consists of two segments, one to detect errors and to throw
The
e r r o r

ceptions and to take appropriate actions. exceptions, and the


catch
the
to
other

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

throw exception; 1/ Block of statements which


// detects and throws an
exception

catch (type arg) // Catches exception

// Block of statements that


// handles the exception

ke cach en the try block


throws an exception, the program control leaves the try block and enters the eatch statement of
rOWS
at
exceptions are objects used to transmit information about a problem. If the type of object
376
Object-Oriented Programming with C executed for
handling the exception te

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>

using namespace std;


int main ()

int a,b of a and b \n";


<< "Enter Values
cout
cin >> a;
cin >> b;
int x= a-b;
try

if (x != 0)
=" << a/x << "\n";
cout << "Result (a/x)

There is an exception
else //

// Throws int obj ect


throw(x);

catch (int i) // Catches the exception

caught: DIVIDE BY ZERO \N"


cout<<Exception
cout << "END";

return 0;

The output of Program 13.1 would be:

First Run

Enter Values of a and b


20 15
Result (a/x) = 4
END

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

Function that causes


an exception

Invoke
try block
function

Throw Invokes a function that


exception contains an exception

catch block

Catches and handles


the exception

Fig.13.2) Function invoked by try block throwing exception


The general format of code for this kind of relationship is shown below:

type functi on (arg list) / / Function with exception

throw (object) // Throws exception

(Contd.)
ore e d Programm

(Theoretical+Pr Course Code:

378
Object-Oriented Programming with C

try

Invoke function here

//Catches excepti on
catch (type arg)

Handles exception here

without any code


between them.
immediate after try block
Catch block must be
Note
function that generates
an exception.
demonstrates howa try block invokes a
Program 13.2

Function that
Generates Exception
Program 13.2 Invoking

Throw point outside the try block


//
#include <iostream>

using namespace std;

void divide (int x, int Y, int z)

cout "\nWe
<< are inside the function \n"
if ( (x-y) I= 0) / / It is OK

int R = z /(x-y);
cout << "Result = " << R << "\n";

else // There is a probl em

throw(x-y)i // Throw point

int main ()

try

cout << "We are inside the try block \n";


divide (10,20,30); // Invoke divide ()
(Contd)
379

EXception Handling

divide (10,10,20) // Tnvoke divide()


catch (int 1) 7/ Catches the exception

cout << "Caught the exception \n'"

return 0;

of the Program 13.2 would be:


The output
inside the try block
We are
inside the function
We are
Result = -3

the function
We areinside
Caught the exception

13.4 THROWING MECHANISM


the throw statement in of the
that is desired to be handled is detected, it is thrown
one
when an exception using
following forms:

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.

Note Syntax of throw is same as that of return.

13.5 CATCHING MECHANISM


Asstated 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 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

Multiple Catch Statements


t 1s
such cases, we
possible that a program segment has more than one condition to throw an exception. In such we e
can
dow ass06i
more than one catch statement with a try (much like the conditions in a switch statement) as shown belowe

try

// try block

catch (typel arg)

/ / catch block1

catch (type2 arg)

// catch block2

catch (typeN arg)

// 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

Multiple Catch Statements


Program 13.3 Mu
13.3
include <iostream>

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"

catch (char c) // Catch 1

cout << Caught a character \n";

m) // Catch 2
cat ch (int
cout << Caught an integer \n'"

catch (double d)D // Catch 3

cout << Caught a double \n";

cout << "End of try-catch system \n \n";

int main ()

cout << Testing Multiple Catches \n"


cout << "x == 1 \n";

test (1)
cout << "x == 0 \n"

test (0)
cout << "x == -1 \n"
test (-1);
cout << "x == 2 \n";

test(2):
return 0;

The output of the


Program 13.3 would be:
Testing Multiple Catches
= 1
Caught an integer
End of
try-catch system
382
Object-Oriented Programming with Ct
X ==0
Caught a character
End of try-cat ch system

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

and it completes normal execution, control passes to the f


When the try block does not throw any exceptions first
with that try block.
statement after the last catch handler associated

when the test() is invoked with X= 2.


Note try block does not throw any exception,

Catch All Exceptions


of exceptions and therefore may not be able to
In some situations, may not be able to anticipate all possible types
we
such circumstances, we can force a catch statement to catch al
design independent catch handlers to catch them. In
the catch statement using ellipses as
exceptions instead of a certain type alone. This could be achieved by defining
follows:

catch (. . .)

// Statements for processing


// all exceptions

Program 13.4 illustrates the functioning of catch(..).

Program 13.4 Catching all Exceptions

#include <iostream>

using namespace std;

void test (int x)

try
(Contd)
383
Exception Handing

i f (x= 0) throw x; // int


i f (x- -1) throw 'x' // char
if (x== 1) throw 1.0; // Eloat

catch (..) // catch all

cout << MCaught an exception \n"

int m a i n 0

cout << Testing Generic Catch \n"


test (-1);
test (0)
test(1)
return 0;

the Program 13.4 would be:


The output of
Testing Generic Catch

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

Catching Class Types as Exceptions


s always a good practice to create custom objects corresponding to different types of errors. The objects can then be
stably handled by exception handlers to take necessary action. Program 13.5 demonstrates the catching of a class type
as exception:

Program 13.5 Class Type as an Exception

#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) ;

void err_display (void)

cout<<\nError Code: "e<err_codec<"


\n"<<"Error Description :
"<<err desc;

int main ()

try
"

to throw a test exception. ;


Cout<< "Press any key
cin.get ();
throw Error (99, "Test Exception");

catch (Error e)
"

cout<<"\nException caught successfully.


e.err_display () ;

return 0;

The output of Program 13.5 would be:


LIMITATION
Press any key to throw a test exception .
C++ compiler does not check if any
Exception caught successfully .

exception is caught or not, unlike


Error Code: 99 JAVA.
Error Description : Test Exception

13.6 RETHROWING AN EXCEPTION


A handler may decide to rethrow the exception caught without processing it. In such situations, we may simply in
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 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

using namespace std;

divide louble x, double y)


void

cout << Inside function n"


try

i f (y == 0.0)
throw Y: // Throwing double
else
cout << Division =
"
<< x/y << "\n";

catch (double) // Catch a double

cout << Caught double inside function \n";


throw; 7/ Rethrowing double

cout << "End of function \n\n";

int main ()

cout << "Inside main \n";


try

divide (10.5,2.0)
divide (20.0,0.0);
catch (double)

cout << "Caught double inside main \n";

cout << "End of main \n";

return 0;

The output of the Program 13.6 would be:

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

13.7 SPEcIFYING EXCEPTIONS


It is possible to restrict a function to throw only certain specified exceptions. This is achieved by adding a thro.s
to the function definition. The general form of using an exception specification is:

type funct ion (arg-1ist) throw (type-1ist)

Function body

The type-list specifies


the type of exceptions that may be throOwn.
ThroWing any ther type of exception
wille
abnormal program termination. If we wish to prevent a function from cause
throwing any exception, we may do so by ma
the type-list empty. That is, we must use king
throw(); // Empty list
in the function header line.

Note A function can only be restricted in what


types of exceptions it throws back to the try block
that called it. The restriction applies only when
throwing an exception out of the function (and
not within a function)

Program 13.7 demonstrates how we can restrict a function to throw only certain types and not all.

Program 13.7 Testing Throw Restrictions

#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;

The output of the Program 13.7 would be:


Testing Throw Restrictions
X == 0

terminate called after


Aborted (core dumped)
throwing an instance of 'char
ne
program terminated abnormally because the function
'test) is meant to throw only int and double
type exceptions.
Note lf no
matching catch statement is found, the exception will not be
caught. So for precautionary
measure, use terminate() function.
Another point to be kept in mind, is that this feature of
restricting a function to throw a limited
types exception is not supported evenly by all C++ Compilers. Some do not
of
Teature, while some others support only some of it. Programmers support the
before using the feature. should exercise caution
388

Object-Oriented Programming with Ct

13.8 EXCEPTIONS IN CONSTRUCTORS AND DESTRUCTORS


What will happen if an exception is thrown while executing a constructor routine? Since, the object is not
control goes out of the object's context.
constructed; its destructor would not be called once the program And, if the
was raised, then there
Would be no mechanism t
constructor had reserved some memory before the exception to p
mechanism must be implemented pertaining to the oVen
Such memory leak. Hence, appropriate exception handling

routine to handle exceptions that occur during object construction.


Inside the constructor block or inside mais0
Now, the question arises as to where shall we catch the exception? If we
allow the exception to be handled inside main then we would not be able to prevent the memory leak situation s
within the constructor block so that we get the chance to
that
ee
discussed earlier. Thus, we must catch the exception
must simultaneously rethrow the exception to be apPpropriately handled
any reserved memory space. However, we ide
the main block. This scenario is illustrated in the following code:

class A

public:

try

data-type d1;
//Constructor code

throw e

catch (e)

delete d1; /Deleting the allocated memory before re

//thrOwing the exception


throw 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 ( )

//Bxception handl ing code

13.9 EXCEPTIONS IN OPERATOR OVERLOADED FUNCTIONSs


may incorporate exception handling mechanism in an operator overloaded function definition to
systemhandle
nerated or user specified exceptions. Recall Program 7.2 in which we had overloaded the + binary operator to
mnute the sum of two complex numbers. The following code depicts the handling of user-specified exception of
adding a zero to the complex number object.

class complex

public
class FLAG{}; //Abstract class FLAG

complex complex ::operator+ (complex c)


if (c.x==0 && C.y==0)
throw FLAG ();
complex temp;
temp.x=X+C .X;
temp.y-y+C.y;
return (temp);

catch (complex: : FLAG)

coutee"Add Zero Exception";

You might also like