0% found this document useful (0 votes)
2 views14 pages

Unit V Exception

The document provides an overview of exception handling in C++, explaining the concepts of synchronous and asynchronous exceptions, and the keywords try, catch, and throw. It details the mechanics of throwing and catching exceptions, including multiple catch statements and re-throwing exceptions, as well as the use of standard exceptions from the <exception> class. Additionally, it discusses exception specifications and the process of stack unwinding when exceptions are thrown.
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)
2 views14 pages

Unit V Exception

The document provides an overview of exception handling in C++, explaining the concepts of synchronous and asynchronous exceptions, and the keywords try, catch, and throw. It details the mechanics of throwing and catching exceptions, including multiple catch statements and re-throwing exceptions, as well as the use of standard exceptions from the <exception> class. Additionally, it discusses exception specifications and the process of stack unwinding when exceptions are thrown.
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/ 14

Unit V Exception Handling

Exceptions: Exceptions are runtime anomalies or unusual conditions that a program may
encounter while executing .Anomalies might include conditions such ass division by zero,
accessing an array outside of its bounds or running out of memory or disk space. When a
program encounters an exception condition, it must be identified and handled.

Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.

Types of exceptions:There are two kinds of exceptions

1.Synchronous exceptions

2.Asynchronous exceptions

1.Synchronous exceptions:Errors such as “Out-of-range index” and “over flow” are synchronous
exceptions

2.Asynchronous exceptions: The errors that are generated by any event beyond the control of
the program are called asynchronous exceptions

The purpose of exception handling is to provide a means to detect and report an exceptional
circumstance

Exception Handling Mechanism:

An exception is said to be thrown at the place where some error or abnormal condition is
detected. The throwing will cause the normal program flow to be aborted, in a raised exception.
An exception is thrownprogrammatic, the programmer specifies the conditions of a throw.

In handled exceptions, execution of the program will resume at a designated block of code,
called a catch block, which encloses the point of throwing in terms of program execution. The
catch block can be, and usually is, located in a different function than the point of throwing.

C++ exception handling is built upon three keywords: try, catch, and throw.

Try is used to preface a block of statements which may generate exceptions. This block of
statements is knownas try block. When an exception is detected it is thrown by using throw
statement in the try block.

Catch block catches the exception thrown by throw statement in the try block and handles it
appropriately.
The structure ofthese two blocks is shown below:

......

......

try

......

throw exception //Block ofstatements which detects and throws an exception

.....

catch(type arg)

...... //Blockof statements that handles the exception

......

......

......
When the try block throws an exception, theprogram control leaves the try blockand enters the
catch statement ofthe catch block. Here exception is nothing but an object used to transmit
theinformation about a problem. If the type of object thrown matches the arg typeof the catch
statement then catchblock is executed for handling the exception.

A program is givenbelow that will explain you that how actually exception handling is done in
C++.

#include<iostream>

using namespace std;

int main()

int x,y,z;

cout<<“Enter the values of x and y:”;

cin>>x>>y;

z=x-y;

try

if(z!=0)

cout<<“Result(x/z)=”<<x/z;

else //division by zero exception

throw(z); //throws int object

catch(int) //catches the exception

{
cout<<“Exception caught: z=”<<z;

return 0;

Outputs of the above program is shown below:

For First Run

For second Run

Multiple catch statements:

A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions.

try

{
//try block

catch(data type1 arg)

//catch block1

catch(data type2 arg)

//catch block2

………………

……………..

catch(data typeN arg)

//catch blockN

• When an exception is thrown, the exception handler are searched in order fore an appropriate
match.

• 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

Write a Program to catch multiple catch statements


#include<iostream.h>

void test(int x)

try

if(x==1) throw x;

else

if(x==0) throw 'x';

else

if(x==-1) throw 1.0;

cout<<"end of try block"<<endl;

catch(char c)

cout<<"caught a character"<<endl;

catch(int m)

cout<<"caught an integer"<<endl;

catch(double d)

cout<<"caught a double"<<endl;

}
int main()

test(1);

test(0);

test(-1);

test(2);

return 0;

Output:

caught an integer

caught a character

caught a double

end of try block

Catch All Exceptions:

All possible types of exceptions and therefore may not be able to design independent catch
handlers tocatch them. In such circumstances, we can force a catch statement to catch all
exceptions instead of a certain type alone.

catch(…)

………

Write a Program to catch all exceptions

#include<iostream.h>

void test(int x)

{
try

if(x==0) throw x;

if(x==0) throw 'x';

if(x==-1) throw 1.0;

catch(...)

cout<<"caught exception"<<endl;

int main()

test(-1);

test(0);

test(1);

return 0;

Re-throwing an Exception:

It is possible to pass exception caught by a catch block again to another exception handler. This
is known as Re-throwing.

#include <iostream>

using namespace std;

void MyHandler()

{
try

throw "hello";

catch (const char*)

cout <<"Caught exception inside MyHandler\n";

throw; //rethrow char* out of function

int main()

cout<< "Main start...."<<endl;

try

MyHandler();

catch(const char*)

cout <<"Caught exception inside Main\n";

cout << "Main end";

return 0;

Specifying Exceptions:
Specification of exception restrict functions to throw some specified exceptions only with the
use of throw(exception list) in the the header of the function.

General form

Type function_name(argument list) throw(exceptions -list)

Statements

try

statements

Exception specification Meaning

throw() The function does not throw any e

throw(...) The function can throw an except

The function can throw an except


throw(type)
type.

Example Description

void Funct() throw(int) The function may throw an int ex

void Funct() throw() The function will throw no except


The function may throw a char* a
void Funct() throw(char*, T)
user defined type exception.

void Funct() or void Funct(...) The function may throw anything

// Another sample function f3() that

//calls f2() and handles exception


Stack unwinding: //thrown by f1()
When we call some functions, it stores the address into call stack, and

after coming back from the functions, pops out the address to start the
void f3() {
work where it was left of.
cout<<"\n f3() Start ";
The stack unwinding is a process where the function call stack entries

try {
are removed at runtime. To remove stack elements, we use exceptions.

If an exception is thrown from the inner function, then all of the entries
f2();
of the stack is removed and return to the main invoker function.

}
So exception handling involves Stack Unwinding if exception is not

handled in same function (where it is thrown).


catch(int i){

cout<<"\n Caught Exception: "<<i;


Explanation
}// Example Exception Specification
In the above program, when f1() throws exception, its entry is removed

cout<<"\n f3() End";


#include <iostream>
from the function call stack (because it f1() doesn’t contain exception

}using namespace std;


handler for the thrown exception), then next entry in call stack is looked for

exception handler. The next entry is f2(). Since f2() also doesn’t have
int main() {function
// handler
f3();
void handler() {
}cout<<"In the handler()\n"; }
handler, its entry is also removed from function call stack. The next entry in

function call stack is f3(). Since f3() contains exception handler, the catch

block inside f3() is executed, and finally the code after catch block.

Standard Exceptions :

In C++ standard exceptions are defined in <exception> class that we can use inside our
programs. The arrangement of parent-child class hierarchy is shown below:

1 std::exception

An exception and parent class of all the standard C++

2 std::bad_alloc

This can be thrown by new.

3 std::bad_cast

This can be thrown by dynamic_cast.

4 std::bad_exception

This is useful device to handle unexpected except


program.
5 std::bad_typeid

This can be thrown by typeid.

6 std::logic_error

An exception that theoretically can be detected by read

7 std::domain_error

This is an exception thrown when a mathematically in


used.

8 std::invalid_argument

This is thrown due to invalid arguments.

9 std::length_error

This is thrown when a too big std::string is created.

10 std::out_of_range

This can be thrown by the 'at' method, for example a


std::bitset<>::operator[]().
11 std::runtime_error

An exception that theoretically cannot be detected by rea


Example for Exception Object
12 std::overflow_error

This#include
is thrown<iostream>
if a mathematical overflow occurs.

#include<exception>
13 std::range_error
int main()
using namespace std;
This is occurred { when you try to store a value which is ou
class ZeroException :public exception
14 std::underflow_error try
{
This is thrown {if a mathematical underflow occurs.
public:
int a,b;
const char* what()
Exception Objects
cout<<"Enter a and b:"<<endl;
The C++ Standard{ library provides a base class specifically designed to declare objects to be
cin>>a>>b;
thrown as exceptions.It is called std::exception and is defined in the <exception> header.

return "Zero division error";


This class has a virtual member function called what() that returns a null-terminated character
sequence (of type char *) and that if(b==0)
can be overwritten in derived classes to contain some sort of
} exception.
description of the

{
};
ZeroException obj;

throw obj;

else

cout<<"a/b = "<<a/b<<endl;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy