You are on page 1of 12

Exception Handling

13
Key Concepts
mechanism Multiple catching Rethrowing
Errors and exceptions | Throwing
exceptions | Exception handling mechanism| Catching mechanism Catching all
exceptions Restricting exceptions throvwn

13.1 Introduction
We know that it is very rare that a program works correctly first time. It might have bugs. The two most
0St
common types of bugs are logic errors and syntactic errors. The logic errors occur due to poor under
standing of the problem and solution procedure. The syntactic errors arise due to poor understanding of
the language itself. We can detect these errors by using exhaustive debugging and testing procedures

We often come across some peculiar problems other than logic or syntax errors. They are known
as exceptions. Exceptions are run time anomalies or unusual conditions that a program mayencaun
ter while executing. Anomalies might include conditions such as division by zero, access to an arcy
outside of itsbounds, or running out of memory or disk space. When a program encountes a
exceptional condition, it is important that it is identified and dealt with effectively. ANSI C++ provoes
built-in language features to detect and handle exceptions which are basically run time errois
Exception handling was not part of the original C++. It is a new feature added to ANST CFT.
almost all compilers support this feature. C++ rated
exception handling provides
a type-sale, inly
approach, for coping with the unusual
predictable problems that arise while executing a prog
m.

13.2 Basics of Exception


Handling
Exceptions are of two kinds, namely, synchronous Errors

such as "out-of-range index' and "over-flow" exceptions and asynchronous excepro eos
belong to the
en

thatare caused by events beyond the control of the synchronous type exceptioi alled
f

asynchronous program (such


keyboard
exceptions. The
proposed exception handling
as
interrupaned t0
handle only synchronous exceptions. mechanism in C++ 5

The purpose of the exception handling r e p o r ta n

mechanism is to provide means to


"exceptional circumstance so that appropriate e s t sa

aREDMI NOJi5code that performs the action can be taken. The mechanli deteue1ggest
CO 48MP QUAD CAMERA following tasks:
Excoption landling 345
1, Find the problem
(Hit the exception)
o Inform that an error has occurred (7hrow the oxception)
3 Receive the error information (Catch the oxcoption)
4.Takecorrective actions (Handle the oxception),

aror handling code basically consists of two


segments, one to detect errors
ntions, and the other to catch the exceptions.and to, take appropriate and to throw
actions.

13.3 Exception Handling Mechanism


C++ exception handling mechanism is
try block basically built upon
three keywords, namely, try,
word
throw, and catch. The key
try is used to preface a block of statements (sur
Detects and throws rounded by braces) which may generate exceptions. This
an exception block of státements is known as try block. When an eKcep
tion is detected, it is thrown using a throw statement in the
try block. A catch block defined by the keyword catch
Exception catches' the exception thrown' by the throw statement in
object the try block, and handles it ap ropriately. The relationship
catch block is shown in Fig. 13.1.

Catches and handles The catch block that catches an exception must imme-
the exception diately follow the try block that throws the exception. The
general form of these two blocks are as follows:
Fig. 13.1 The block throwing exception

try

// Block of statements whi ch


throw exception; detects and throws a n excepti
on
//

// Catches exception
catch (type arg

Block of statements that


//
/ handles the exception

the
block and enters
the program control leaves the try
exception, information
REDMINOTE8 throws an used to transmit
exceptions are objects
Note that

48MP QUAD EAMEBDlOck.


the gram is ab
ent, then o
346
This
Dlock
about when no exception is detecteedwith
nelp the abort() function which is invoked.by default.
of the
a
is
control
simple
Program
Object thrown
odk is skipt
goes
problem.
executed
Oriented
try-catch
toIf
13.1
return
the
for
the
else
type
include Try
0;
handling
Programming
<iostream>
statement
mechanism
of
/7
using namespace std;
the
object
Block
is
with
int main () There
immediately
C++
exception.
int a, b; thrown
illustrated
"Enter Values is of a and b \n";
cout <<
cin >> a Throwing
an
If
in
after
matches
cin >> b;
they
int x a-b the
Program
do
an
the
try exception
catch
not
arg
i f(x != 0) 13.1.
block.
type
cout << "Result (a/x)
match,
<
Exception
a/x << n ;
in
That
the
is,
progr
catch
the
throw (x) ; /Throws int object
catch
stateme
hile
catch (int i) // Catches the exception and
cout<<"Exception caught: DIVIDE BY ZERO\N";
thre

cout < END"

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
2 Enter Values of a and b
ron10 10 ooldp
Exception Handling 347

Exception ught: DIVIDE BY ZERO


no
ENP be
Program detects and catches a division-by-zero problem. The output of first run shows a success-
tion. When no exception is thrown, the catch block is skipped and execution resumes with
ful execution
hefirst line after the catch. In the second run, the denominator x becomes zero and therefore a
the i r
tuation occurs. This exception is thrown using the object x. Since the exception
division-by-zero situa
hiect is an int type, the catch statement containing int type argument catches the exception and
object
displays necessary message.

Most often, exceptions are thrown by functions that are invoked from within the try blocks. The
noint at which the throw is executed is called the throw point. Once an exception is thrown to the
atch block, control cannot return to the throw point. This kind of relationship is shown in Fig. 13.2.

Throw point

Function that causes


an exception

oilonut s eolovni ooid yd s wor e


Invoke
function
try block

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


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

Ype function (arg 1ist) // Function with exception

// Throws exception
throw(object)

try
OO
(Contd.)
with C++
348 Object Oriented Programming

here
Invoke functi on

exception
// Cat ches
catch (type arg)

Handles exception here

catch block, irespective of the location of tha ike


NOTE: The try block is immediately followed by the throw
point.

Program 13.2 demonstrates how a try block invokes a function that generates an exception

Program 13.2 Invoking Function That Generates Exception

/ / 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)!= 0) /1 It is OK

int R =
2/ (x-y)
cout<< Result=" << R << \n"
else /1 There is a
problem
throw (-y) / Throw point

int main ()

try

cout << We are inside


the try block \n

(Contd)
ew enims Exception Handling 349
o
divide (10, 20, 30) ;
7/ Invoke divide ()
divide (10, 10,20);
nen osn so// Invoke divide ()o
catch (int i)
// Catches the exception
cout<< Caught the
exception \n";
return 0;

rlateo srt i bece ciqmie e ud roace hafoct


nodesoxo
The output of the Program 13.2 would be:
omeste role0 stqlu
We are inside the try block
o nerd s1om.zsd insmpee mapoq s lsih oldle coga
Weare inside the tunction)no g9lele relsa efo rens enoh olsiodes
Result = -3 rooro goesd
Polad rowote es(rornslele taiie
We are inside the function
Caught the exception

13.4 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.
hat 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.
Inany case, control is transferred to the catch statement.

13.5 ts a Catching Mechanism

ASStated earlier, code for handling exceptions is included in catch blocks. A catch block looks like
d Tunction definition and is of the form
elnoredhle rloisa Msrevee to al amuprs Jsnt aldoeai
catch (type ag) boiuchye el ony nolqe3xe orli aniolsm ent velbnd tat ent esene

e Statements fOr oso oinilam srerr olqmsko elgrie s awore &.ch ensigo
managing exceptions
cnoligsoxsloaeqeiauo
350 Object Oriented Programming with C++

The type indicates the type of exception that catch block handles. The parameter arn
arg is a
parameter name. Note that the exception-handling code is placed between two braceOption
statement catches an exception whose type matches with the type of catch argument optonal
The catth
ent. When tis
caught, the code in the catch block is executed.

If the parameter in the catch statement is named, then the parameter can be tuo.
exception-handling code. After executing the handler, the control goes to the statement im the
following the catch block. immediately
Due to mismatch, if an exception is not caught, abnormal program termination will ocir
important to note that the catch block is simply skipped if the catch statement does not calch It is
an
exception.

Multiple Catch Statements


It is possible that a program segment has more than one condition to throw an exception. In s
Such
cases, we can associate more than one catch statement with a try (much like the conditions i
in a
switch statement) as shown below:

try
{
// try block
h on
catch (typel arg)

//catch block1 T3ol pniwoliot ert to eroi


cat ch (type2 arg)
7/ catch block2

ceo oeis eii anslerooenoyo.ocy6 10ed ke losido bnsTogoerll

catch(typeN arg)emeeenolseif d houe90 2 otoeoxe


// catch blockN

dneoow

When an exception is thrown, the exception handlers are searched in order for an iate
approprd
match. The first handler that yields a match is executed. After executing the handler, the controlgoes
tothe first statement after the last catch block for that
try. (In other words, all other handiei are

bypassed). When no match is found, the program is terminated.

Itis possible that arguments of several catch statements match the Such
of
cases,the first handler that matches the exception type is executed. type exceptio
an

Program 13.3 showS a simple example where mutiple catch statements are used to hande var
OUs types of exceptions.
Exception Handling 351

Program 13.3 Multiple Catch Statements


#include <iOstream>
using namespace std;
void test (int x)

try

i f (x= 1) throw x / int


else
if (x = 0) throw x 1/ char
else
if(x 1) throw 1.0; // double
cout << End of try-block n
catch (char c) /7 Catch 1

Cout KK
Caught a character n

catch (int m) / Catch 2

cout < Caught an integer \n

catch (double d)
/ / Catch 3

cout <<Caught a double \n


re b6
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

ne output of the Program 13.3 would be:


Testing Multiple Catches
X 1
Caught an integer
Endof try-catch sysLem OO
with C++
Programming
Oriented
352 Object

X=0
Caught a character

system
eote
try-catch
End of

Caught a double

system
End of t r y - c a t c h

X 2
End of try-block
system
End of try-catch
with xx= 1 and 4..
invokes the
function test() =

and therefore
The program when
executed first,

This matches the type ofthe parameter


m in catch2 and therefore thhander
rows xan
int exception.
execution, the
function test() is again invoked with
executed. Immediately after the and therefore the first handler ie .

the function throws'x', a charactertype exception inaly


a double type exception
is thrown. Note that eva
the handler catch3 is executed when
y ime only the
executed and all other dlers
handle are bypassed.
handler which catches the exception is

throw any exceptions and it Completes normal execution


When the try block does not Control
handler assOciated with that try block
statement after the last catch
passes to the first

NOTE: try block does notthrowany exception, when the test) is invoked with x=2

Catch All Exceptions


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

catch (...

/StatementS for processing


// all exceptions

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

Program 13.4 Catching all Exceptions


#include <iostream
usingnamespace std; BLoW eer mbgor erioe
void test (int x)
ntiooEXCeption Handling 353
try

i f(x 0) t.hrow
if (x=-1) throw x // int
x'
i f(x= 1) throw 1.0; // char
/ Eloat
catch. )
/ catch all
cout <<
Caught an
exception n

int main ()

Cout <<Testing Generic Catch \n"


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

The output of the Program 13.4 would be:

Testing Generic Catch


Caught an exception
Caught an exception
Caught an exception

NOTE: Note that all the throws were caught bythe catch(. statement
default statement along with other catch handlers
t may beagood idea to use the catch(...) as a

not handled explicitly.


SOthat it can catch all those exceptions which
are

placed last in the list of handlers. Placing it before other catch


OTE: Remember, catch(..) should always be
exceptions.
OGKS WOuld preventthose blocks from catching
ed bluow tmergor9 Ro Juqtuo erlT
atching Class Types as Exceptions
of errors. The
It is a corresponding to different types
to create custom objects
ys a good practice 13.5
to take necessary action. Program
handled by exception handlers
da Can then be suitably as exception:
demonstrates the class
tching of a type
Exception
Prog 13.5
ogram Class Type as an

#1nclude <icostream sibloeb yent 1e/bnar A


Lnclude <stringn so noigeoxe 9 woo o
(Contd.)
C++
354 Object Oriented Programming with

#include <conio.h>

using hanespace std


Class BIror

int err code;


char *err_desC

public
*a)
Brror (int c,char

e r r code=c;
char [strlen (d) ]
err desc=new
d)
strcpy (err_desC,

(void)
void err display
Code: serr_Code < n < " E r r o r Do
cout<< \nError
<err desc

int main ()

try
cout<<PresS any key tO thrOW a t e s te K c e p t i o n . "

getch ()
throw Error (99Test Exception")
catch (Error e)

Coutk nException caught successfully."


e.err display ();
getch ()
return 0

The output of Program 13.5 would be:


anioitqaoxe os 2oqyi ean0 prio
Press any key to throW a test
exception. oles1o ot
soitoso boop 8
Exception caught successfully,s noitqeoxe yd halbnerd videliue ed nort ti alo9p
Error Code: 99

Error Description: Test


Exception

13.6 Rethrowing an Exception


A handler may decide to rethrow the exception situations, We
may simply invoke throw without caught without processing it. In sui
any arguments as shown
below:
throw
Exception Handling 355
1ses the current exception to be thrown
to the next
statement listed after that enclosing
enclosing try block. Program try/catch sequence and Is
int
ht
This

is rethra and caught. 13.6 demons


nstrates how an
by
Kception
a
main
causes

catch
Program () 13.6Rethrowing An Exception
#include statement
<iostreamn>
cout<<
i
using nameSpace std

voiddivide (double X, double y)


Caught
cout << Inside function \n"
try
double
i f(y== 0.0)
throw Y Throwing double
else
inside
Cout <<Division <x/y <<\n";

catch (double) // Catch a double


function

// Rethrowing double
throw
\n";
cout << End of function \n\n";
e
yd ce ouyenwolf

Cout << I n s i d e main \n";


try eheon 0
divide(10.5,2.0)
divide(20.0,0.0)

catch (double)
e
fepee
inside main \n
cout << "Caught double

COut << End of main \n

return 0;

be:
Output of the Program 13.6 would
Inside main
Lnside function

You might also like