Adobe Scan 06 May 2024
Adobe Scan 06 May 2024
Exception Handling
13.1 Introduction
Fxception handling allows you to manage runtime errors in a
ongoing procesS and in near future we may see systematic manner It
is still an
exception handling, Some examples of runtime errors or Some more tools for
exception are
Division by zero
array index out-of-range
arithmetic overflow
unexpected arguments
file not found etc.
The purpose of the exception handling
and report an exceptional mechanism is to provide means to detect
circumstance so that appropriate action can be taken.
In this chapter, we will discusS Some of the exception handling techniques of C++.
Note that., some old compilers do not support theexception-handling mechanism.
Chapter Objectives
On completion of this chapter, you will be able to :
Define exception.
Write the various ways of handling exception.
List the examples of exceptions.
Explain the exception handling constructs -try, throw, catch.
Use multiple catch in a try block.
Use of catch all exceptions.
Nested-try blocks
Handling uncaught exception
Standard exceptions
(407)
13.2 Ways of Handling Exceptions
Errors occurringat runtime i.e. after clean compilation is called exceptions. The
exceptions can be handled in many ways.
1. Not doing anything - this will happen by default - in such a case the program
execution willterminate causingloss of data and may be some damages. This
is not agood way, hence should be avoided.
2. Another way could be just displaying the error message on the screen and
proceeding further.
3. Call exit(int) function. If integer returned is zero, it is a normal exit after
successfully completing the task. If the number returned is non-zero, then the
exitcan be treated as normal but some clean up tasks are still pending.
4 Calling abort( ) terminates program execution abruptly.
5. Handling the exception with the help of standard C++ features. This is the best
way.
catch (exception) {
Il code to handle exception
Here. we have placed the code that might generate an exception inside the try block.
Every try block is followed by the catch block.
When an exception oc urs, the throw statement throwS an exception, which is
caught by the catch block.
The catch block cannot be used without the try block.
try
If (b!= 0)
cout << a/b;
else
throw 2;
catch (int i)
When the try block throws an exception, the program control jumps to the catch
statement ofthe catch block and catch block is executed for handling the exception.
When no exception is detected and thrown, the control goes to the statement
immediately after the cat h block.
Note that exceptions are objects used to transmit information about a problem. If
the type of object thrown matches the argument type in the catch statement,
then catch block is executed, otherwise the program is aborted with the help of the
abort( ) function which is invoked by default.
Example 13.4
Program to illustrate the try-catch mechanism
PROGRAM : P181.CPP
#include <iostream.h>
#include <conio.h>
void main()
inta,b;
clrscr();
cout<<"Enter two integer numbersn'";
cin>>a>>b;
(411)
try
if(b != 0)
cout<<"Result = "Kalh;
else
throw(2); Ithrow int object
Run 1:
Enter two integer members
10 2
Result = 5
Run 2:
This program detects and catches a division-by-zero problem. The output of first
run showsasuccessfulexecution. In the second run, the denominator bbecomes
zero and therefore a division-by-zero situation occurs. This exception is thrown
using integer object and the catch statement containing int type arugment catches
the exception and displays necessary message.
Most often, exceptions are thrown by functions that are invoked trom within the try
blocks. The point at which the throw is executed is called the throwpoint. Once
an exception is thrown tothe catch block, control cannot return to the throw point.
The figure 13.1 illustrates this concept.
(412)
Throw Point
Throw Exception
Invoke
try Block Function
Throw Invokes a function
exception that contains
an exception
catch block
FIGURE 13.1
is
The general format of code for this kindof relationship
try
| invoke function
exception
Il catches and handle the
(413)
Example 13.5
Program to illustrates how a try block invokes a function that gernerates execption,
PROGRAM : P182.CPP
void main()
try
cout<<"Exception occurred'";
getch();
Run :
inside the try block
inside the function
Result = 5
inside the function
Exception occurred
(414)
Self Check-1
1. Write a program to handle the division by zero exception using class.
Answers/ Hints to Self Check-1
1. #include <iostream.h>
#include <conio.h>
class sample
protected:
int a, b;
public :
void div( );
}:
void sample :: div( )
try
void main()
sample obj:
obj.div( );
(415)
13.5Order of Catchblocks
condition
It is
possible that program segment has more than one to
exception. In such Cases, we can have multiple catch blocks with one trythrow
a block.an
In C++, when multiple catch blocks are present after atry block, they are
in the order they appear. The order of catch blocks is significant evaluated
matches exceptions to catch blocks based on the order of the
because
order of
C++
appearance. The first catch block whose exception type matches the thrown
their
exception type will be executed and subsequent catch blocks will be
Consider the following example : ignored.
try
Il try block
llcatch block 1
Ilcatch block 2
catch block i
In this example, if an exception of type 1in thrown within the try block. it
caught and handled by the first catch block and will be
subsequent
ianored. If an exception of type 2 is thrown, it will be catch blocks will be
caught by the second catch
block and so on.
(416)
Exampie 13.6 (Multiple Catch)
For Multiple catch, study the following program segment
void div()
int a, b, C;
try
cin >> a>> b;
If (a = 0) && (b== 0)
throw 'x'; I/ character object
else
if (b == 0)
throw 2 Il integer object
else
C=alb;
}
catch (int i) W
integer argument
cout << "Division-by zero exception":
}
catch (char ch) Il character argument
cout <<"0/0 exXception';
In thËs example, after the try block, we have two catch blocks. The first catch block
is invoked when the exception throws an integer. The second catch block is invoked
when the exception throws a character. Hence, there must be a match between the
type thrown and type of argument of the catch block.
13.6 Catch all exceptions
t is possible to 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 shown below:
catch (...)
(417)
Example 13.7
Program to illustrate the catch all exception.
#include diostream. h>
#inclue <conio.h>
void sample(int a)
try
void main( )
sample(-l);
sample(0);
sample(1);
Run :
Exception occurred
Exception occurred
Exception occurred
void main()
try
I/Some code
try
IISome code
catch(ExceptionA a)
IISome code
catch(...)
{
I/Some exception handling
In this example :
There are two try blocks; the outer try block and the inner try block.
Inside the inner try block, an exception is thrown.
The inner catch block catches this exception and handle it.
Since the exception is caught within the inner try block, the outer try block
continues executing normally, and the program does not enter the outer catch
block.
Nested try blocks are useful for handling exceptions at different levels of code
exeCution and providing more specific error handling for different parts of the progrem.
however, it's essential to use them iudiciously to avoid overly complex excepuon
handling logic.
(419)
C++program to illustrate the use of nested try blocks
#include <iostream.h>
Il tunction throwing exceptions
void func(int n)
if (n<10) {
throw 22;
else{
throw 'c';
Void main()
try {
try {
cout<<"Throwing exception from inner try blockn";
func(2):
catch (intn){
cout << "nner Catch Block caught the exception\n";
catch (char c) {
cout << "Outer catch block caught the exception\n"
Run :
Throwing exception from inner try block
Inner catch block caught the exception
Out of the block
(420)
More we used func() function to throw two exceptions of int and har type. Wa
Used an inner try block to catch integer exceptions. Now, whenever the try blocks
throw an exception, the control moves outwards trom the nested block illthe
matching catch block is found. In this case, it was the inner catch block that caught
the exception.
void demohandler()
int main()
return 0;
Run :
(422)
13.9Standard Exception
standard excoptionsdefnndt
C++ provides a list of
the header file
We should include
#include cexception.h>
that we Can use f ug
C++ has provided us with a numberof standard excoptions
tablo below
shown inthe
exception handling. Some of them are
Exception Description
Summary
run-time error isexception.
The most appropriate name for
exception are division-by-zero, array index out-of-range.
Some example of
not found etc.
arithmetic overflow, unexpected argument, file
compilers do not support the exception handling mechanism.
Some old
C+t+ are handled through the following three keywords : try, throw
" Exceptions in
and catch.
EXERCISE
(424)