0% found this document useful (0 votes)
7 views27 pages

Exception Handling: Bibha Sthapit Asst. Professor Ioe, Pulchowk Campus

Chapter 9 discusses exception handling in programming, particularly in C++. It covers the types of errors, the mechanism of exception handling using try, throw, and catch blocks, and various methods to handle exceptions, including multiple catch blocks and re-throwing exceptions. Additionally, it addresses uncaught exceptions, unexpected exceptions, and provides examples of implementing a stack using exception handling.

Uploaded by

ishangautam099
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)
7 views27 pages

Exception Handling: Bibha Sthapit Asst. Professor Ioe, Pulchowk Campus

Chapter 9 discusses exception handling in programming, particularly in C++. It covers the types of errors, the mechanism of exception handling using try, throw, and catch blocks, and various methods to handle exceptions, including multiple catch blocks and re-throwing exceptions. Additionally, it addresses uncaught exceptions, unexpected exceptions, and provides examples of implementing a stack using exception handling.

Uploaded by

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

Chapter 9:

Exception Handling
BIBHA STHAPIT
ASST. PROFESSOR
IOE, PULCHOWK CAMPUS
Introduction
• Two common types of error in a program are:
– 1) Syntax error (arises due to missing semicolon, comma, and
wrong program constructs etc)
– 2) Logical error (wrong understanding of the problem or wrong
procedure to get the solution)

• Exceptions are the errors occurred during a program


execution. Exceptions are of two types:
– Synchronous (generated by software i.e. division by 0, array bound
etc).
– Asynchronous (generated by hardware i.e. out of memory, 2
keyboard etc).
Introduction
• The purpose of exception handling mechanism is to detect
and report an exceptional circumstances so that appropriate
action can be taken. The mechanism for exception handling
is:
1.Find the problem(hit the exception).
2.Inform that an error has occurred(throw the exception).
3.Receive the error information(Catch the exception).
4.Take corrective actions(Handle the exception).

3
Exception handling mechanism
• C++ exception handling mechanism is basically built upon
three keywords namely, try, throw and catch.

• Try block hold a block of statements which may generate an


exception.
– The try block is the one that can throw an exception. The code that is
to be monitored for exceptions is placed within this block. Thus, the
try block is the scope of exception generation. Whenever a specific
code segment is expected to throw an exception, such segment is
placed within the try block. Thus, this block contains either a throw
statement or a function containing either a throw statement or a 4
similar function inside the body.
Exception handling mechanism
• When an exception is detected, it is thrown using a throw
statement in the try block.
– This is a mechanism to generate the exception. It is usually a single
statement starting with the keyword throw or a function call that
contains throw inside its body. After the execution of this statement,
the control is transferred to the corresponding catch block written
immediately after the try block, if the exception is thrown.
– The identifier following the throw is the name of the variable being
thrown. The control now is permanently transferred to the catch block
and the statements after the throw statement are not executed.
5
Exception handling mechanism
• A try block can be followed by any number of catch blocks.
– This is the section where the exception is handled. There are two
ways to throw an exception: first, by using an explicit throw
statement or second, by calling a function which in turn contains
a throw statement or a similar function call in its body. The
exception is handled by the catch block, which should
immediately follow the try block.

6
Exception handling mechanism
• The general form of try and catch block is as follows:
try
{
/* try block;
throw exception*/
}

catch (type1 arg)


{
/* catch block*/
} 7
1. W/O function and exception class

main()
Output:
{ int a,b;
1st Run:
cout<<“Enter two numbers (num/den):";
cin>>a>>b;
try Enter two numbers (num/den):8 2
{ if (b==0) Result=4
throw b;
else
2nd Run:
cout<<“Result=“<<a/b;
}
catch(int x) Enter two numbers (num/den):4 0
{ cout<<"Denominator cannot be zero"; } Denominator cannot be zero
}

8
2. Exception generated by function

void divide (int a, int b) Output:


{ if (b==0)
throw b;
Result=2
else
Denominator cannot be zero
cout<<"Result="<<a/b<<endl;
}
main()
{ try
{ divide(6,3);
divide(5,0);
}
catch(int x)
{ cout<<"Denominator cannot be zero"; }
} 9
3. Exception class
main()
class numbers
{
{ int a, b;
numbers n;
public:
try{
class div_zero{ };// Exception class
void divide() n.divide();
{ n.divide();
cout<<"enter two numbers (num/den):"; }
cin>>a>>b; catch(numbers::div_zero)
if (b==0) { cout<<"Denominator cannot be zero"; }
throw div_zero(); }
else Output:
cout<<"Result="<<a/b<<endl;
enter two numbers (num/den):9 3
}
Result=3
};
enter two numbers (num/den):7 0
10
Denominator cannot be zero
Multiple exception handling
• In some situations the program segment has more than one
condition to throw an exception. In such case more than one catch
blocks can be associated with a try block as shown:
try { //try block
}
catch(type1 arg)
{ //catch block1
}
catch(type 2 arg)
{ //catch block 2
}
……………..
catch (type N arg)
{ //catch block N 11
}
main() catch(int i)
{ {
Output:
int n; cout<<"Integer exception caught";
1st run:
cout<<"Enter any integer value:"; }
Enter any integer value: -9
cin>>n; catch(char ch)
Double exception caught
try {
{ cout<<"char exception caught";
2nd run:
if(n==0) }
Enter any integer value: 0
throw 1; catch(double d)
Integer exception caught
if (n>0) {
throw '1'; cout<<"Double exception caught";
3rd run:
if (n<0) }
Enter any integer value: 12
throw 1.0; }
Character exception caught
}
12
Catch all exception
• In some cases when all possible type of exceptions cannot be
anticipated and may not be able to design independent catch
handlers to catch them
• In such situations a single catch statement is forced to catch all
exceptions instead of certain type alone.
• This can be achieved by defining the catch statement using
ellipses as follows
catch(. . .)
{
//statement for processing all exceptions
}
13
main()
{ int n;
cout<<"Enter any integer value:"; Output:

cin>>n; 1st run:


try Enter any integer value: -9
{ An exception caught
if(n==0)
throw 1; 2nd run:
if (n>0) Enter any integer value: 0
throw '1';
An exception caught
if (n<0)
throw 1.0;
3rd run:
}
Enter any integer value: 12
catch(. . .)
{ cout<<“An exception caught"; An exception caught
}
} 14
Re-throwing exception
• A handler may decide to re-throw an exception caught without
processing them. In such situations we can simply invoke throw
without any argument like
throw;
• This cause the current exception to be thrown to the next enclosing
try/catch sequence and is caught by a catch statement listed after
that enclosing try block.

15
int main() Output:
void divide(int x, int y)
{ { Inside main
cout<<" Inside Function \n"; cout <<"Inside main \n"; Inside Function
try try
Result =5
{ if (y== 0) { divide(10,2);
divide(20,0); End of function
throw y; //throwing int
else }
cout<<"Result =" << x/y<<endl; catch (int) Inside Function
} {
Caught int inside a function
catch(int) //Catch a int cout <<"Caught int inside main \n";
Caught int inside main
{ }
cout <<"End of main\n "; End of main
cout<<"Caught int inside a function \n";
throw; //re-throwing int return 0;
} }
cout<<"End of function\n\n";
}
16
Exception specification for function
• In some cases it may be possible to restrict a function to throw only certain
specified exceptions. This is achieved by adding a throw list clause to function
definition. The general form of using an exception specification is:
Ret_Type function (arg-list) throw (type-list)
{
// function body
}
• The type list specifies the type of exceptions that may be thrown. Throwing any
other type of exception will cause abnormal program termination. To prevent a
function from throwing any exception, it can be done by making the type list empty
like throw(); in the function header line.
• Similarly, include throw(…); in function header line to throw all types of exceptions.

17
void test(int n)throw(double,int) main() Output:
{ { cout<<"Inside main\n";
cout<<"Inside function\n"; try Inside main
if(n==0) testing throw restrictions
{ cout<<"testing throw restrictions\n";
throw 1; Inside function
if (n>0) test(23);
terminate called after
throw '1'; test(0); throwing an instance of
if (n<0) 'char'
}
throw 1.0; catch(int i)
cout<<"End of function\n";
{ cout<<"Integer exception caught\n"; }
}
catch(char ch)
{ cout<<"character exception caught\n"; }
catch(double f)
{ cout<<"Double exception caught\n"; }
cout<<"End of main\n"; 18
}
Exception with argument
class numbers
void divide()
{
{
int a, b;
cout<<"enter two numbers (num/den):";
public:
cin>>a>>b;
class div_zero// Exception class
if (b==0)
{
throw div_zero(b,"Divide by zero");
public:
else
int err_no;
cout<<"Result="<<a/b<<endl;
char err_name[50];
div_zero(int num, char *name)
}
{ err_no=num;
};
strcpy(err_name,name);
}
19
};
Exception with argument(contd.)
main() Output:
{
numbers n; enter two numbers (num/den):65 5
try{ Result=13
n.divide(); enter two numbers (num/den):65 0
n.divide(); Exception Caught:0Divide by zero
}
catch(numbers::div_zero z)
{ cout<<"Exception Caught:"<<z.err_no<<z.err_name;

}
} 20
Handling uncaught exception
• If no handler at any level catches the exception, the special library
function terminate( ) (declared in the <exception> header) is automatically
called. By default, terminate( ) calls the library function abort( ) , which abruptly
exits the program.

• This terminate() function is modifiable as per user requirements. To change the


terminate handler, we use set_terminate() which is defined under <exception>
class as:
set_terminate(defined_terminate_handler)

• The terminate handler set by set_terminate() should be a function that take no


argument and do not have return type. It must stop program execution and it
must not return to program or resume it in any way.
21
void test(int n) main()
{
{
set_terminate(my_uncaught_handler);
cout<<"Inside function\n"; cout<<"Inside main\n";
if(n==0) throw 1; try
if (n>0) throw '1'; {

if (n<0) throw 1.0; test(-3);


}
cout<<"End of function\n";
catch(int i)
} { cout<<"Integer exception caught\n";
}
void my_uncaught_handler() cout<<"End of main\n";

{ }
Output:
cout<<"Uncaught exception found\n";
Inside main
abort(); Inside function 22
} Uncaught exception found
Handling unexpected exception
• The special function unexpected( ) is called when we throw something other than
what appears in the exception specification. The default unexpected( ) calls
the terminate( ) function.

• But this behavior can be redefined by calling set_unexpected. This function is


automatically called when a function throws an exception that is not listed in
its dynamic-exception-specifier (i.e., in its throw specifier).

• This function is provided so that the unexpected handler can be explicitly called by
a program, and works even if set_unexpected has not been used to set a
custom unexpected handler (calling terminate in this case)

23
main()
void test(int n)throw(int)
{ set_unexpected(my_unexpected_handler);
{ cout<<"Inside main\n";
cout<<"Inside function\n"; try

if(n<0) throw 1; {

if (n>=0) throw '1'; test(23);


}
cout<<"End of function\n";
catch(int i)
}
{ cout<<"Integer exception caught\n"; }
catch(char c)
void my_unexpected_handler() { cout<<“Character exception caught\n"; }
{ cout<<"End of main\n";

cout<<"Unexpected exception raised"; }


Output:
}
Inside main
Inside function 24

Unexpected exception raised


STACK USING EXCEPTION:
void push(int x)
class my_stack
{ if(top==SIZE-1)
{ throw FULL();
int *a; a[++top]=x;
int SIZE; }
int top; int pop()
public: {

class EMPTY{ }; if(top==-1)

class FULL{ }; throw EMPTY();


return a[top--];
my_stack(int n)
}
{
void display()
top=-1;
{
SIZE=n;
for(int i=0;i<=top;i++)
a=new int[n];
cout<<a[i]<<ends;
25
}
} };
do

main() {

{ switch(ch)

int item,sz; {

cout<<"\nEnter the size of stack:"; case 1:

cin>>sz; cout<<"\nEnter the item to push:";

my_stack s(sz); cin>>item;


try

int ch=1; {

cout<<"\nStack with Exception Handling"; s.push(item);

cout<<"\n\n\tMENU\n1.PUSH\n2.POP\n }

3.SHOW STACK\n4.EXIT"; catch(my_stack::FULL) //FULL object is caught

cout<<"\nEnter your choice:"; {

cin>>ch; cout<<"\n***Stack Overflow***\n";


}
26
break;
case 3:

case 2: cout<<"\nThe Stack is:\n";


try try
{ { s.display(); }
cout<<"\nPoped Item is:"<<s.pop(); catch(my_stack::EMPTY)
} {
catch(my_stack::EMPTY) //EMPTY object caught cout<<"\n***Stack Empty***\n";

{ }
cout<<"\n***Stack Empty***\n"; break;
} case 4:
break; exit(0);
}
cout<<"\nEnter your choice:";
cin>>ch;
}while(ch<5); 27
}

You might also like