Exception Handling
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.
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
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),
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
// Catches exception
catch (type arg
the
block and enters
the program control leaves the try
exception, information
REDMINOTE8 throws an used to transmit
exceptions are objects
Note that
First Run
Second Run
2 Enter Values of a and b
ron10 10 ooldp
Exception Handling 347
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
catch block
// Throws exception
throw(object)
try
OO
(Contd.)
with C++
348 Object Oriented Programming
here
Invoke functi on
exception
// Cat ches
catch (type arg)
Program 13.2 demonstrates how a try block invokes a function that generates an exception
#include <iostream>
int R =
2/ (x-y)
cout<< Result=" << R << \n"
else /1 There is a
problem
throw (-y) / Throw point
int main ()
try
(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;
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.
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.
try
{
// try block
h on
catch (typel arg)
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
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
try
Cout KK
Caught a character n
catch (double d)
/ / Catch 3
test (0)
cout< x=-1 \n"
test(-1)
cout << x = 2 \n"
test (2)
return 0
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,
NOTE: try block does notthrowany exception, when the test) is invoked with x=2
catch (...
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 ()
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
#include <conio.h>
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)
catch
Program () 13.6Rethrowing An Exception
#include statement
<iostreamn>
cout<<
i
using nameSpace std
// Rethrowing double
throw
\n";
cout << End of function \n\n";
e
yd ce ouyenwolf
catch (double)
e
fepee
inside main \n
cout << "Caught double
return 0;
be:
Output of the Program 13.6 would
Inside main
Lnside function