0% found this document useful (0 votes)
33 views11 pages

Module - 5 - Exception Handling - Lecture Notes 17181774532320

This document provides an overview of exception handling in C++, detailing the types of errors (logical and syntactic) and the concept of exceptions as runtime anomalies. It explains the try-catch mechanism, the use of throw statements, and how to handle multiple exceptions with catch blocks. Additionally, it covers advanced topics such as catching all exceptions, catching class types, and rethrowing exceptions.

Uploaded by

Dhanush HM
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)
33 views11 pages

Module - 5 - Exception Handling - Lecture Notes 17181774532320

This document provides an overview of exception handling in C++, detailing the types of errors (logical and syntactic) and the concept of exceptions as runtime anomalies. It explains the try-catch mechanism, the use of throw statements, and how to handle multiple exceptions with catch blocks. Additionally, it covers advanced topics such as catching all exceptions, catching class types, and rethrowing exceptions.

Uploaded by

Dhanush HM
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/ 11

MODULE 5: EXCEPTION HANDLING

INTRODUCTION
The common types of error in the programs would be logical errors and syntactic errors. The logic errors occur
due to poor understanding of the problem and syntactic errors arise due to the poor understanding of the
programming language. These errors can be found out by debugging and testing procedures. Other than logic
and syntax errors there are certain problems that occur during program execution these are known as
exceptions.
Exceptions are run time anomalies or unusual condition that a program may encounter while executing.
Anomalies might include conditions such as division by zero, access to an array outside its bounds or running
out of memory or disk space.

BASICS OF EXCEPTION HANDLING


There are two types of exceptions synchronous exception and asynchronous exceptions. Errors such as “out-of-
range index” and “over-flow” belong to the synchronous type exceptions. The errors that are caused by events
beyond the control of the program (such as keyboard interrupts) are called asynchronous exceptions. The
proposed exception handling mechanism in C++ is designed to handle only synchronous exceptions.
The purpose of the exception handling mechanism is to provide means to detect and report an
“exceptional circumstance” so that appropriate action can be taken. The mechanism suggests a separate error
handling code that performs the following tasks:
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).
The error handling code basically consists of two segments, one to detect errors and to throw exceptions, and
the other to catch the exceptions and to take appropriate actions.

EXCEPTION HANDLING MECHANISM

C++ exception handling uses three keywords try, throw and catch. Try block contains the statements that
generate the exceptions. When an exception is detected, it is thrown using a throw statement in the try block. A
catch block catches the exception thrown by the throw statement in the try block and handles it appropriately.
The relationship between the blocks is shown in the above figure.
The catch block that catches an exception must immediately follow the try block that throws the
exception. The general form of these 2 blocks are as follows:

Reshma, Dept of CSE


MODULE 5: EXCEPTION HANDLING

When the try block throws an exception the program control leaves the try block and enters the catch statement
of the catch block. Exceptions are objects that are used to transmit information about a problem. If the type of
object thrown matches the arg type in the catch block then the catch block is executed for handling the
exception. If they do not match the program is aborted with the help of the abort( ) function which is invoked
by default. When no exception is detected and thrown the control goes to the statement after the catch block.

Program: try-catch mechanism


#include<iostream>
Using namespace std;
int main ( )
{
int a,b;
cout << “Enter the values of a and b \n”;
cin >> a;
cin >> b;
int x = a-b;
try
{
If (x!=0)
{
cout << “Result (a/x) = “ << a/x << “\n”;
}
else //There is an exception
{
throw(x); //Throws int object
}
}
catch (int i) //Catches the exception
{
cout <<”Exception caught: DIVIDE BY ZERO\n”;
Reshma, Dept of CSE
MODULE 5: EXCEPTION HANDLING
}
cout << “END”;
return 0;
}
Output
First Run
Enter the Values of a and b
20 15
Result (a/x) = 4
END
Second Run
Enter the Values of a and b
10 10
Exception caught: DIVIDE BY ZERO
END
Working of the program: the program detects and catches a division-by-zero problem. The output of the first
run throws a successful execution. When no exception is thrown the catch block is skipped and execution
resumes with the first line after the catch. In the second run the denominator x becomes zero and therefore a
division-by-zero situation occurs. This exception is thrown by using object x the catch block containing int
argument will catch the exception and handle it.

THROW POINT, TRY AND CATCH BLOCKS


Exceptions are thrown by functions that are invoked from within the try blocks. The point at which the throw is
executed is called the throw point. Once an exception is thrown to the catch block, control cannot return to the
throw point as shown in figure below.

Reshma, Dept of CSE


MODULE 5: EXCEPTION HANDLING
The general format of code for this kind of relationship is as shown below:

Program: Invoking the function that generates exception


//Throw point outside the try block
#include<iostream>
Using namespace std;
void divide ( int x, int y, int z)
{
cout << “\n We are inside the function \n”;
if((x-y)!=0)
{
int R = z/(x-y);
cout << “Result = “ << R << “\n”;
}
else
{
throw (x-y);
}
}
int main ( )
{
try
{
cout << “\n We are inside the try block \n”;
divide(10,20,30); //invoke divide ( )
divide(10,10,20); //invoke divide ( )
}
catch ( int i) //catches the exception
{
Reshma, Dept of CSE
MODULE 5: EXCEPTION HANDLING
cout << “Caught the exception \n”;
}
return 0;
}
Output
We are inside the try block

We are inside the function


Result = -3

We are inside the function


Caught the exception

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;
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, which
means the control exits the current try block and is transferred to the catch block after that try block.

CATCHING MECHANISM
Catch block handles the exception. A catch block looks like a function definition and is of the form:
catch (type arg)
{
// Statements for managing exceptions
}
The type indicates the type of exception that catch block handles. The exception-handling code is placed
between two braces. The catch statement catches the exception whose type matches with the type of catch
argument. When it is caught the code in the catch block is executed.
If the parameter in the catch statement is named, then the parameter can be used in the exception-
handling code.

MULTIPLE CATCH STATEMENTS


A program can contain more than one condition to throw an exception. In such cases we can write more than
one catch statement with a try as shown below.
When an exception is thrown the exception handlers are searched in order for an appropriate match.
The first handler that matches is executed. After executing the handler the control goes to the first statement
after the last catch block for that try.
It is possible that arguments of several catch statements match the type of an exception. In such cases,
the first handler that matches the exception type is executed.

Reshma, Dept of CSE


MODULE 5: EXCEPTION HANDLING

Program: Multiple Catch Statements


#include<iostream>
using namespace std;
void test (int x)
{
try
{
if (x ==1) throw x; // int
else
if(x==0) throw ‘x’; // char
else
cout << “End of try-block \n”;
}
catch (char c) // catch 1
{
cout << “Caught a character \n”;
}
catch (int m) // catch 2
{
cout << “Caught a integer \n”;
}
catch (double d) // catch 3
{
cout << “Caught a double \n”;
}
cout << “End of try-catch system \n\n”;
}
int main ( )

Reshma, Dept of CSE


MODULE 5: EXCEPTION HANDLING
{
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;
}

Output:
Testing Multiple Catches
x == 1
Caught an integer
End of try-catch system

x == 0
Caught an character
End of try-catch system

x == -1
Caught an double
End of try-catch system

x == 2
End of try-block
End of try-catch system

Working of the Program: The program when executed first, invokes the function test( ) with x = 1 and
therefore throws x an int exception. This matches the type of parameter m in catch2 and catch2 handler is
executed. After this execution test () with x=0 is invoked, so throw x is a character exception and catch1
handler is executed similarly test () with x = -1 and x=2 is exceuted and the cprresponding handlers are
executed.

Catch All Exceptions


Sometimes we might not write multiple catch handlers to handle the exceptions, In such cases we can write a
single catch statement to catch all exceptions instead of a certain type alone. It is written as follows:
catch (…)
{
// Statements for processing all exceptions
}

Reshma, Dept of CSE


MODULE 5: EXCEPTION HANDLING
Program: Catching all Exceptions
#include<iostream>
using namespace std;
void test ( int x)
{
try
{
if (x == 0) throw x; // int
if (x == -1) throw ‘x’; // char
if (x == 1) throw 1.0; // float
}
catch (…) // catch all
{
cout << “Caught an exception \n”;
}
}
int main ( )
{
cout << “Testing Generic Catch \n”;
test (-1);
test (0);
test (1);
return 0;
}

Output:
Testing Generic Catch
Caught an exception
Caught an exception
Caught an exception

Catching Class Types As Exceptions


Objects are created corresponding to different types of errors. The objects can be suitably handled by exception
handlers to take necessary actions.
Program: Catching of a class type as exception
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main(void)
{
int values[10];
int iDx;
cout<<"Enter the array elements : ";
for(int i=0;i<10;i++)
Reshma, Dept of CSE
MODULE 5: EXCEPTION HANDLING
{
cin>>values[i];
}

try
{
//generate a random index and test repeatedly 10 times
while(1)
{
cout<<"Enter the index of element in the array : ";
cin>>iDx;
if(iDx < 0 || iDx >=10)
{
cout << "Generated index " << iDx << " is invalid" << endl;
throw logic_error("Array out of Bounds");
}
cout << "Given index is " << iDx << " the value at that index is : " << values[iDx] << endl;
}
}
catch (logic_error& e){
cout << "Processing error " << endl << e.what() << " exception occured.\n" << endl;
}
return 0;
}

Rethrowing An Exception
A handler may decide to rethrow the exception caught without processing it. In such situation we can invoke
throw without any arguments:
throw;
This causes 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.
Program: Rethrowing An Exception
#include <iostream>
using namespace std;
void divide (double x, double y)
{
cout << “Inside function \n”;

Reshma, Dept of CSE


MODULE 5: EXCEPTION HANDLING
try
{
if (y == 0.0)
throw y; // Throwing double
else
cout << “Division =” << x/y << “\n”;
}
catch (double)
{
cout << “ Caught double inside function \n”;
throw; // Rethrowing double;
}
cout << “End of function \n\n”;
}
int main ( )
{
cout << “Inside main \n”;
try
{
divide(10.5,2.0);
divide(20.0,0.0);
}
catch (double)
{
cout << “ Caught double inside main \n”;
}
cout << “ End of main \n”;
return 0;
}

Output:
Inside main
Inside function
Division = 5.25
End of function

Inside main
Caught double inside function
Caught double inside main
End of function

When an exception is rethrown it will not be caught by the same catch statement or any other catch in that
group. It will be caught by an appropriate catch in the outer try/catch sequence only.
A catch handler itself may detect and throw an exception. The exception thrown will not be caught by
any catch statements in that group. It will be passed to the next outer try/catch sequence for processing.
Reshma, Dept of CSE
MODULE 5: EXCEPTION HANDLING

Reshma, Dept of CSE

You might also like