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

Module 5

Module 5 of BPLCK 205D focuses on Exception Handling in C++, detailing the types of exceptions, their handling mechanisms using try, throw, and catch keywords, and the benefits of using exception handling in programming. It also covers advanced topics such as multiple catch statements, rethrowing exceptions, specifying exceptions, and standard exceptions provided by the C++ library. The module emphasizes the importance of effective error management to improve program reliability and maintainability.

Uploaded by

pikachunobi44
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)
4 views11 pages

Module 5

Module 5 of BPLCK 205D focuses on Exception Handling in C++, detailing the types of exceptions, their handling mechanisms using try, throw, and catch keywords, and the benefits of using exception handling in programming. It also covers advanced topics such as multiple catch statements, rethrowing exceptions, specifying exceptions, and standard exceptions provided by the C++ library. The module emphasizes the importance of effective error management to improve program reliability and maintainability.

Uploaded by

pikachunobi44
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

BPLCK 205D Module 5

DEPT OF CSE, BKIT


Module-5
Exception Handling
Introduction:-
Usually there are mainly two type of bugs, logical errors and syntactic errors. The logical errors
occur due to poor understanding of problem and syntactic errors arise due to poor understanding of
language. There are some other problems called exceptions that are run time anomalies or unused
conditions that a program may encounter while executing.
These anomalies can be
 Division by zero
 Access to an array outside of its bounds
 Running out of memory
 Running out of disk space
When a program encounters an exceptional condition it is important to identify it and dealt with it
effectively. An exception is an object that is sent from the part of the program where an error occurs
to that part of program which is going to control the error.
Basics of Exception handling:-
Exceptions are basically of two types namely, synchronous and asynchronous exceptions.
Errors such as “out of range index” and “over flow” belongs to synchronous type exceptions. The
errors that are caused by the events beyond the control of program(such as keyboard interrupts) are
called asynchronous exceptions. 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).

The error handling code mainly consist of two segments, one to detect error and throw
exceptions and other to catch the exceptions and to take appropriate actions.
Exception handling mechanism:-
C++ exception handling mechanism is basically built upon three keywords namely try,throw
and catch.
 The keyword try is used to preface a block of statements which may generate
exceptions. This block of statement is called try block.
 When an exception is detected it is thrown using throw statement in the try block.
 A catch block defined by the keyword catch ‘catches’ the exception thrown by the
throw statement in the try block and handles it appropriately. The catch block that
catches an exception must immediately follow the try block that throws the exception.
The general form for this is

DEPT OF CSE, BKIT


try
{
throw exception;
}
catch(data_type arg)
{
//some code
}

When the try block throws an exception, the program control leaves the try block and enters the
catch statement of the catch block. If the type of object thrown matches the arg type in the catch
statement, then the catch block is executed for handling the exception. If they do not match, the
program is aborted with the help of abort() function which is executed implicitly by the compiler.
When no exception is detected and thrown, the control goes to the statement immediately after the
catch block i.e catch block is skipped. The below diagram will show the mechanism of exception
handling

Figure :-The block throwing exception

Benefits of Exception Handling:


Exception handling in C++ provides several benefits that make it an important part of modern
programming. Some of the main benefits of exception handling in C++ are:
 Improved Error Handling: Exception handling in C++ provides a clean and efficient way to
handle runtime errors in a program. It separates error-handling code from normal code,
making the code cleaner and easier to maintain.
 Better Program Structure: Exception handling helps to improve the structure of a program
by allowing developers to separate error-handling code from the main logic of the program.
This makes the code more readable and easier to understand.
 Reduced Complexity: Exception handling can reduce the complexity of a program by
providing a unified mechanism for handling different types of errors. This allows developers
to write simpler and more maintainable code.

DEPT OF CSE, BKIT


 Enhanced Performance: Exception handling can enhance the performance of a program by
providing a fast and efficient way to handle errors. It is faster than using traditional error-
handling methods, such as error codes, which can slow down a program’s execution.
 Increased Flexibility: Exception handling in C++ provides increased flexibility by allowing
developers to define their own exceptions and custom error-handling routines. This allows
developers to tailor the error-handling mechanism to the specific needs of their program.
 Improved Debugging: Exception handling makes it easier to debug a program by providing
a clear and concise way to handle errors. It allows developers to locate and fix errors more
quickly, which can save time and resources.
In conclusion, exception handling in C++ provides several benefits that make it an essential part of
modern programming. It allows developers to write cleaner, more maintainable, and more efficient
code, making it an important tool for developing robust and reliable software.
Throwing mechanism:-
When an exception is encountered it is thrown using the throw statement in the following form:
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.In other words the control exits the try block and transferred
to catch block after the try block.Throw point can be in the deep nested scope within the try block or
in a deeply nested function call.
Catching mechanism:-
Code for handling exceptions is included in catch blocks. The catch block is like a function
definition and is of form
Catch(type arg)
{
statements for managing exceptions
}
The type indicates the type of exception that catch block handles. The parameter arg is an optional
parameter name. The catch statement catches an exception whose type matches with the type of
catch argument. When it is caught, the code in the catch block is executed. After executing the
handler, the control goes to the statement immediately following in catch block. Due to mismatch ,if
an exception is not caught abnormal program termination will occur.In other words catch block is
simply skipped if the catch statement does not catch an exception.
Multiple Catch Statements:-

DEPT OF CSE, BKIT


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 below
try
{
//try block
}
catch(type1 arg)
{
//catch block1
}
catch(type 2 arg)
{
//catch block 2
}
……………..
…………….
catch (type N arg)
{
//catch block N
}
When an exception is thrown, the exception handlers are searched in order for an appropriate
match. The first handler that yields a match is executed. After executing the handler, the control goes
to the first statement after the last catch block for that try. When no match is found, the program is
terminated.If in some case the arguments of several catch statements match the type of an
exception,then the first handler that matches the exception type is executed.

The below program shows the example of multiple catch statements.

#include<iostream.h>
#include<conio.h>
void test(int x)
{
try
{
if (x > 0)
throw x;
else
throw 'x';
}
catch (int x)
{
cout << "Catch a integer and that integer is:" << x;
}
catch (char x)
{
cout << "Catch a character and that character is:" << x;

DEPT OF CSE, BKIT


}
}
void main()
{
clrscr();
cout << "Testing multiple catches\n:";
test(10);
test(0);
getch();
}
Sample Output
Testing multiple catches
Catch a integer and that integer is: 10
Catch a character and that character is: x

Catch All Exceptions:-


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
}
The below program illustrate the functioning of catch(…)
#include<iostream.h>
void test(int x)
{
try
{
if(x==1)throw x; //int
if(x==0) throw 'x'; //char
if(x==-1) throw 1.0; //float
}
catch(...) //catch all
{
cout<<"caught exception"<<endl;
}
}
int main()
{
test(-1);
test(0);
test(1);
return 0;
}

DEPT OF CSE, BKIT


Output:
caught exception
caught exception
caught exception
We can use the catch(. . .) as a default statement along with other catch handlers so that it can catch
all those exceptions that are not handled explicitly.

Rethrowing an Exception:-
A handler may decide to rethrow 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. The following program shows how an
exception is rethrown and caught.
/* Example of 'rethrowing' an exception. */
#include<iostream>
using namespace std;
void sub(int i,int j)
{
try
{
if(i==0)
{
throw i;
}
else
cout<<“Subtraction result is: “<<i-j<<endl;
}
catch(int i)
{
cout<<“Exception caught inside sub()\n”;
throw;
}
};
int main()
{
try
{
sub(8,4);
sub(0,8);
}
catch(int k)
{
cout<<“Exception caught inside main()\n”;
}

DEPT OF CSE, BKIT


return 0;
}
OUTPUT:
Subtraction result is: 4
Exception caught inside sub()
Exception caught inside main()
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 the an appropriate catch in the outer try/catch sequence for
processing.

Specifying Exceptions:-
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:
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(); //empty list in the function header line.

The following program will show this


#include < iostream >
using namespace std;
void test(int x) throw(int,double)
{
if(x==0) throw ‘x’; // char
else
if(x==1) throw; // int
else
if(x==-1) throw 1.0; // double
cout<<“End of the function block \n”;
}
void main()
{
try
{
cout << “Testing throw restrictions \n”;
cout << “X==0 \n”;
test(0);
cout << “x==1 \n”;

DEPT OF CSE, BKIT


test(1);
cout << “x==-1 \n;
test(-1);
cout << “x==2 \n”;
test(2);
}
catch(char c)
{
cout << “caught a character \n”;
}
catch(int m)
{
cout << “caught an integer \n”;
}
catch(double d)
{
cout << “caught a double \n”;
}
cout << “End of try catch system \n\n”;
}
Output:
Testing Throw RESTRICTIONS
x==0
caught a character
End of try catch system

C++ Standard Exceptions


The C++ library has some built-in standard exceptions under the <exception> header which can be
used in our program. The standard exceptions are arranged in a parent-child class hierarchy. Refer to
the image shown below for better visualization.

DEPT OF CSE, BKIT


C++ Exception Classes
Let us learn the hierarchal standard exception classes that come under exception handling in c++.
Class Name Use Case

std::exception is the parent class of all the standard C++ exceptions.


std::exception
So, it contains declarations and definitions of other exceptions.
std::bad_alloc is the type of exception thrown by the allocation
std::bad_alloc
functions to report failure to allocate storage.

std::bad_cast is the type of exception thrown when a dynamic_cast to


std::bad_cast
a reference type fails the run-time check.

std::bad_exception is used to handle unexpected exceptions in a C++


std::bad_exception
program.

std::bad_typeid is the type of exception thrown when a typeid


std::bad_typeid operator is applied to a dereferenced null pointer value of a
polymorphic type.

std::logic_error exception is the type of exception that can be


std::logic_error
theoretically detected by reading the code.

std::domain_error is the type of exception thrown when a


std::domain_error
mathematically invalid domain is used.

DEPT OF CSE, BKIT


Class Name Use Case

std::invalid_argument is the type of exception thrown due to invalid


std::invalid_argument
arguments.

std::length_error is the type of exception thrown when a too big


std::length_error
std::string is created.

std::out_of_range is the type of exception that report errors when we


std::out_of_range
are trying to access elements which is outside of the defined range.

std::runtime_error exception is the type of exception that


std::runtime_error
theoretically cannot be detected by reading the code.

std::overflow_error exception is the type of exception thrown if a


std::overflow_error
mathematical overflow occurs.

std::underflow_error exception is the type of exception thrown if a


std::underflow_error
mathematical underflow occurs.

std::range_error is the type of exception thrown if a mathematical


std::range_error
underflow occurs.

DEPT OF CSE, BKIT

You might also like