0% found this document useful (0 votes)
10 views

Adobe Scan 06 May 2024

Uploaded by

Priyanshu Kumar
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)
10 views

Adobe Scan 06 May 2024

Uploaded by

Priyanshu Kumar
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/ 18

13

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.

13.3Exception handling Model


The exception handling model in C++ is based on three main keywords : try, catch
and throw.
1. Try : The try block encloses the code that might throw an exception. If an
exception is thrown within the try block, the control is transferred to the nearest
matching catch block.
2. Catch: The catch blockis used to handle exceptions. It follows the try block
and contains code that handles specific types of exceptions. When an
exception is thrown within the try block, the control is transferred to the
corresponding catch block (if one exists) that matches the type of the thrown
exception.
3 Throw: the throw keyword is used to explicitly throw an exception within the
try block. It typically takes an exception object as an argument, which can be
of any type (including built-in types or user-defined types).
In C++, we handie exceptions with the help of the try and catch blocks,
the throw keyword.
along with

try - code that may raise an exception


(408)
throw - throws an exception when an error isdetected
catch -code that handles the exception thrown by the throw keyword
Exampie 13.1
The basic syntax for exception handling in C++ is :
try {
Il code that may raise an exception
throw argument:

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.

13.4 Exception Handling Constructs


The C++ language has provided the following keywords to deal with exceptions.
" try
" throw
" catch
Ine exception handling mechanism performs the folowing tasks.
1. Detect the error (Hit the exception)
2. Inform that an error has occurred (throw the exception)
3. Receive the error information (catch the exception)
4. Take the appropriate actions (Handle the exception)
must be prefixed by the
niook OT Statenents in which an exception can occur
exception
Keyword try. This block of statements is known as try block. When an
IS detected, it is thrown using a throw statement in the try block.
(409)
Example 13.2
The code where we expect an exception to occur will be inserted|in atry block as
given below:

try

If (b!= 0)
cout << a/b;
else
throw 2;

This code detects and throw the division-by-zero


problem. In this example, if b is
not zero then output of division wil be
displayed. If b is zero, i.e. division by-zero
situation occurs. This exception is thrown to someone who can
handle it.
Acatch block defined by the keyword catch
catches the exception thrown by the
throw statement in the try block and handles it
appropriately.
Example 13.3
The above division-by-zero exception can be
caught in catch block as given below

catch (int i)

cout << "Exception


occurred:b=" <<b;

Since the exception object (throw 2 )is an int type, the


catch statement containing
int type argument, catches the
exception and displays necessary message. The
catch block that catches an exception must
immediately follows the try block that
throws the exception. The general form of these two
blocks are as follows :
(410)
try
I/ try block
throwexception; / detects and throws an exception

catch (type arg)


I/catch block
I|catch and handles the exception

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

catch(int i) I/lint argument

cout<<"Exception occurred:b= "<<h:


}
getch);
}

Run 1:
Enter two integer members
10 2

Result = 5
Run 2:

Enter two integer numbers


5

Exception occurred : b=0

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

Catches and handles


the exception

FIGURE 13.1
is
The general format of code for this kindof relationship

returntype functionname (arglist)


{
throw(object); I| throwpoint

try
| invoke function

catch (type arg)

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

#include <iostream. h>


#include <conio.h>

void divint a,int b)

cout<<'"inside the functionn";


if(b !=0)
cout<<"'Result = "<<alb;
else
throw(2); IIthrow point

void main()

try

cout<<"inside the try blockn'";


div(10,2); Ilinvoke the function div()
div(5,0);
catch(int i) Ilint argument

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

cout <<" Enter two integer numbers n";


cin >> a >> b;
If (b !=0)
cout <<" Result ="<<a/b:
else
throw 2;
}
catch (int i)

cout <<" division by zero eXception occurred \ n";

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

catch (type 1arg)

llcatch block 1

catch (type 2 arg)

Ilcatch block 2

catch (type iarg)

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

I Statements that handle the exception

(417)
Example 13.7
Program to illustrate the catch all exception.
#include diostream. h>
#inclue <conio.h>
void sample(int a)
try

f(a == -l) throw 2; I/int object


f(a == 0) throw 'm' / char object
f (a= =1) throw 5.0 W
float object
}
catch (.. .) Ilcatch all

cout << " Exception occurred n'";

void main( )

sample(-l);
sample(0);
sample(1);

Run :
Exception occurred
Exception occurred
Exception occurred

13.7 Nested try Blocks


Nested try blocks in C++ allow for more granular
levels of code execution. Atry block can contain exception handling within differet
finercontrol over exception handling. When an another try block within it. enabling
try block, the program exception is thrown within an inner
searches an appropriate catch block within that inner
for
hiock first. If not found, the search
continues in the enclosing outer try blocks.
(418)
Here's an example demonstrating nested try biocks:

void main()

try

I/Some code
try
IISome code

catch(ExceptionA a)

I/Some specific exception handling

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"

cout <<"Out of the block":


return 0;

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.

13.8Handling Uncaught Exception in C++


In C++, uncaught exceptions are those exceptions that are not handled by any
catch block.
Whenever an exception arises in C++, it is handled as per the behavior defined
usingthe try-catch block. However, there is often the case when an exception is
thrown but isn't caught because the exception handling subsystem fails to find a
matching catch block for that particular exception.
In that case, the following set of actions takes place :
1 The exception handling subsystem calls the function: unexpected(). This
function, provided by the default C++ library, defines the behavior when an
uncaught exception arises. By default, unexpected calls terminate().
2 The terminate function defines the actions
that are to be performed during
process terminatior. This, by default, calls abort().
3 The process is aborted.
The terminate() and unexpected() simply call other functions to
error. As explained above, terminate calls abort(), and actually handle an
Thus, both functions halt the program execution whenunexpected) calls terminate).
an exception handlingerror
0Ccurs.

13.8.1 The unexpected() function


When afunction with an exception specification throws an
listed in its exception specification, the C++ runtime does theexception that is not
1 following:
The unexpected() function is called.
2 The
unexpected() function cals the function pointed to by unexpected _handler.
Bydefault, unexpected_handler points to the function
You can replace the default value of
terminate().
function set_unexpected(). unexpected_handler Witn tne
13.8.2 The terminate() function
In some cases, the exception handling mechanism fails. If no handler at any level
catches the exception, the special library function terminate( )(declared in
ne <exception> header) is automatically called. By default, terminate( )calls
the Standard C++ library function abort(), which abruptly exits the
program
(421)
terminate() is called directly by the program, the terminate_handler is the one
most recently set by a call to set terminate(). If set_terminate) has not yet been
called, then terminate()calls abort().
The following program demonstrates how to set a custom termination handler
#include <exception.h>
#include <iostream.h>
Il definition of custom termination function

void demohandler()

Cout <<"Inside new terminate handlernn";


abort():

int main()

llset new terminate handler


set_terminate(demohandler);
try{
cout <<"Inside try blockn":
throw 50;

catch (char a) l/ won't catch an int exception

cout << "Inside catch blockn";

return 0;

Run :

Inside try block Inside try block


Inside new terminate handler

(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

bad alloc Thrown when a dynarnic mernory allocation fails.


badcast Thrown by C++ when an attempt is made to perforn a
dynamic_cast to an invalid type.
bad_exception Typically thrown when an exception is thrown and it
cannot be rethrown

bad_function_call thrown by empty function objects

in Gtt. These exceptions are defined in


There are many other standard exceptions
header file.
the exception

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.

typically caused by a faulty statement in a try block. The


An exception is catch
discovers the error and throws it, which is caught by a
Statement
statement.
(423)
The catch is similar to a function with an argument list. The argument list will
correspondtothe expected otbjects. For example, to catch an integer, we have
a catch block with integer as the argument.
Acatch block must follow a try block.
There can be more than one catch blocks for a try block.
It is also possible to make a catch statement to catch all types of exceptions
using ellipses as its argument.
catch
Uncaught exceptions are those exceptions that are not handled by any
block.
C++ provides many standard exception defined in header <exception>.

EXERCISE

1. What do you mean by exception ?


2. Howis an exception handled in C++?
3. What are the advantages of using exception handlingmechanism in a program?
4 What are the various ways of handling exceptions ? Which one is best?
5 Describe the exception handlingmechanism by giving examples.
6 Write aprogram of multiple catch in a try block.
7. List the Common examples of exceptions.
8. If no exceptions are thrown by a try block,where does the controlgo after completing
the statements in the try block.
9. Write aprogram toread two numbers m andn andevaluate x given by
1 1
X= +
m n

Use exception handling to throw an exception in case division by zero is attempted.


10. Write a program that illustrate the application of multiple catch statements.
11. Explain unexpected() and terminate() function.
12. Explain some standard exception.
13. Explain the concept of handling uncaught exceptions.

(424)

You might also like