0% found this document useful (0 votes)
11 views33 pages

Unit 5 Exception

This document provides an overview of exception handling in C++, detailing the types of errors (syntax, logical, runtime) and the mechanisms for handling exceptions using try, throw, and catch keywords. It explains the classification of exceptions, the structure of exception handling, and the use of user-defined exceptions and multiple catch statements. Additionally, it covers the handling of uncaught exceptions and the use of unexpected and terminate functions for managing errors.

Uploaded by

G.Chandra Shekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views33 pages

Unit 5 Exception

This document provides an overview of exception handling in C++, detailing the types of errors (syntax, logical, runtime) and the mechanisms for handling exceptions using try, throw, and catch keywords. It explains the classification of exceptions, the structure of exception handling, and the use of user-defined exceptions and multiple catch statements. Additionally, it covers the handling of uncaught exceptions and the use of unexpected and terminate functions for managing errors.

Uploaded by

G.Chandra Shekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 33

UNIT-V

1
UNIT – V: Exception Handling-
Introduction, Principles of Exception
Handling, The Keywords try, throw
and catch, Exception Handling
Mechanism, Multiple Catch
Statements, list of exceptions, catch
All exceptions,

Standard Template Libraries –


Containers, Iterators, Functions
2
Types of Errors
• In programming ,there are three types of
errors
I. Syntax error
II. Logical error
III. Runtime error
• Syntax error: This error occurs due to lack of
language. Errors are basic programming
mistakes such as not providing optimistic
number of opening and closing brackets,
semicolon is not added at the termination of
statement. Declaration of an identifier is
missing, grammatical rule mistakes while
3 declaration of an identifier
Types of errors
• Logical error: This error usually occurs when
there is a poor understanding of a problem and
due to mistake in the solution. When this error
occurs it will not be displayed on the screen. The
results will be displayed wrong. Ex. infinite loop.
• Runtime error: This error occurs when output
gets an undetermined value. Ex. Number format ,
Division by 0, array index out of bound.
• Exceptions are some peculiar problems that may
occur other than basic syntax and logical errors.
• For handling these exceptions there are built in
language features provided by ANSI C++.

4
EXCEPTION
• Exceptions are run time anomalies or unusual
conditions that a program may encounter during
execution.
• Conditions such as Division by zero ,Access to an
array outside of its bounds. Running out of
memory, Running out of disk space.
• Main purpose of the Exception handling
mechanism is to provide means to detect and
report an “exceptional circumstance” so that an
appropriate action can be taken.
5
EXCEPTION HANDLING
• Exceptions are classified into two categories.
1.Synchronous exceptions . synchronous exceptions
are generated because of execution of the
instructions . Ex. out of range index and over
flow.(All exceptions are unchecked.)
2.Asynchronous exception. Asynchronous
exceptions are external, program cannot control.
such as keyboard interrupt, file does not exist.
• The C++ exception handling mechanism is
designed to handle synchronous type of
exceptions only.
6
EXCEPTION HANDLING
• The exception handling mechanism in
C++ deals with exceptions by
performing following tasks:
a. Identify the problem (hit the exception) .
b. Inform that an exception has occurred (throw
the exception)
c. Exception handler catches the exception
information (catch the exception)
d. Exception handler takes corrective actions
(handle the exception)
7
Exception handling mechanism
• C++ exception handling mechanism is built upon
following three expressions:
 try :The expression try is used to preface that block may
generate exceptions. This block is often termed as try
block.
 throw:The throw expression is invoked when an
exception is detected. It informs the catch block that an
exception has occurred.
 catch: The exception handling code is enclosed in catch
block. The catch block catches the exception thrown by
the throw expression and handles it in a predefined
manner.
8
TRY, THROW AND CATCH EXPRESSIONS

try {


throw exception;
……………….
}
catch (type arg)
{ ………………..
………………..
}
9
# include <iostream>
using namesapce std;
int main()
{
else
int x,y; {
cout << “enter values of x & y \n”; throw (a);
cin >> x;
cin >> y; }
int a = x-y; }
try
{
catch (int i)
if (a!=0) {
{ cout << “Exception caught a=” << a;
cout << “Result (x/a) =” << x/a;
} }
return(0);
}

10
TRY, THROW AND CATCH EXPRESSIONS
• The throw statement can take multiple forms:
throw (exception);
throw exception;
throw;
• The first two throw statements pass the exception object to
the catch handler,
• third throw statement without any exception object is used
to rethrow an exception from within a catch block.
• If the program fails to provide an exception handler for a
thrown exception, the program will call the terminate()
function.terminate() function will call bydefault abort() to
stop program.
11
Multiple Catch Statements
•Use more than one catch Syntax:
block with the try block. try {
// Your code
•Generally, multiple catch block }
is used to handle different // 1st catch block
types of exceptions means
catch(Exception_Name) {
each catch block is used to
handle different type of
// Code
exception. }
// 2nd catch block
catch(Exception_Name) {
// Code
}

12
catch all
• There is a special catch block called the ‘catch all’
block,
syntax: catch(…){ }
• used to catch all types of exceptions.
include <iostream>
using namespace std;
int main() int is thrown as an exception, but there is
{ no catch block for int, so the catch(…)
try { block will be executed.
throw 10;
}
catch (char *excp) {
cout << "Caught " << excp;
}
catch (...) {
cout << "Default Exception\n";
}
return 0;
}
13
#include <iostream>
Implicit type conversion doesn’t happen
using namespace std; for primitive types. For example, in the
following program, ‘a’ is not implicitly
int main() converted to int.
{ Output:
Default Exception
try {
throw 'a';
}
catch (int x) { cout << "Caught " << x; }
catch (...) {
cout << "Default Exception\n";
}
return 0;
}
14
In C++, try/catch blocks can be nested. Also, an exception can be re-thrown using
“throw; “.
#include <iostream>
using namespace std;
int main() catch (int n) {
{ cout << "Handle remaining ";
try { }
try { return 0;
}
throw 20;
}
catch (int n) {
cout << "Handle Partially ";
throw; // Re-throwing an exception
} }

15
16
User-Defined Exception
• We can use Exception handling with class too.
• Even we can throw an exception of user defined class types.
• User-Defined Exception or custom exception is creating your
own exception class and throwing that exception using the
'throw' keyword.

17
#include <iostream>
using namespace std;
class MyCustomException : public std::exception {
public:
char * what () {
return "Custom C++ Exception";
}
};
int main() {
try {
throw MyCustomException();
} catch (MyCustomException mce) {
cout << "Caught MyCustomException" << endl;
cout << mce.what();
}
}

18
#include <iostream>
using namespace std;
class demo {
};
int main()
{
try {
throw demo();
}
catch (demo d) {
cout << "Caught exception of demo class \n";
}
}

19
#include <iostream> else if (i == 2)
throw demo2();
using namespace std; }
class demo1 { catch (demo1 d1) {
}; cout << "Caught exception of demo1 class \n";
}
class demo2 {
}; catch (demo2 d2) {
cout << "Caught exception of demo2 class \n";
int main() }
}
{ }
for (int i = 1; i <= 2; i++) {
try {
if (i == 1)
throw demo1();

20
inheritance
• When trying to catch exception type of base and
derived classes.

• The base class catch will catch all derived classes


, if base class is first in the catch sequence.

• To catch derived class exception , put derived


class first in the catch sequence

21
inheritance:
include<iostream>
using namespace std;
class B {};
class D: public B {}; catch(B b) {
int main() { cout<<"Caught Base Exception";
}
D derived; return 0;
try { }
throw derived;
}
catch(D derived){
cout<<"Caught Derived
Exception";
}

22
List of Exceptions/Restricting Exceptions
• We can restrict the type of exceptions that function can
throw outside.
• We can specify a list of exceptions that a function can
throw.
• Throwing any other type will cause abnormal program
termination.
• We can specify our own unexpected handler.

23
List of Exceptions/Restricting Exceptions
Syntax
rettype function() throw(type e1,type e2,type e3)
{
…..
}
Void f1(); //function can throw any exception.
Void f2() throw(); //should not throw any
exception
Void f3() throw(A,B);//throw only A, B exceptions

24
Exceptions in No Exception function
void funct throw() /*Indicates that it will not
generate any exception*/
{
…..
}
• If any statement throws an exception the control is
transferred to library function abort(); which
terminates the program by issuing an error
message.

25
Raising an Unspecified Exception
• If the function throws an
exception not listed in its
specifications, the program will
call the function unexpected ()
this will call by default abort()
methos.

• This is runtime issue.

26
Handling Uncaught Exceptions
• Terminate(): Exception is raised and
Handler is not found. Default action
for teminate() function is to invoke
abort() and terminate the program.
• Set_terminate(): Allows the user to
write the function that defines the
programs actions to be taken to
terminate the program when a
handler for the exception cannot be
found.
27
#include<iostream>
using namespace std; catch(excep1)
class excep1{}; {
cout<<"caught excep1"<<endl;
class excep2{};
}
cout<<"I am not displayed"<<endl;
int main() }
{
Output:
try
{ Throwing uncaught exceptions
terminate called after throwing an
cout<<"Throwing uncaught
instance of 'excep2‘
exceptions"<<endl;
throw excep2();
}

28
#include<iostream> try
using namespace std; {
cout<<"Throwing uncaught
class excep1{}; exceptions"<<endl;
class excep2{}; throw excep2();
}
void myexcep() catch(excep1)
{
{ cout<<"caught excep1"<<endl;
cout<<"Myexception }
is invoked"<<endl; cout<<"I am not displayed"<<endl;
}
exit(1);
}
Output:
int main() Throwing uncaught exceptions
Myexception is invoked
{
set_terminate(myexc
ep);

29
Handling Uncaught Exceptions
• Unexpected(): The unexpected function is called when
a function throws an exception not listed in its
exception specifications.
program calls unexpected() function which calls any
user defined function registered by set_unexpected()
function. If no function is registered with it, then it
calls terminate() function.
• Set_unexpected(): Allows the user to write the
function that defines the programs actions to be taken
to throws an exception not listed in its exception
specifications.

30
#include<iostream>
int main()
using namespace std; {
class zero{}; int num;
cout<<"Enter any number"<<endl;
void what_sign(int num) throw()
cin>>num;
try{
{ what_sign(num);
if (num>0) }
catch(...)
cout<<"positive number"<<endl;
{
cout<<"Catch all
else if(num<0) Exceptions"<<endl;
}
cout<<"negative number"<<endl;
cout<<"End of main()"<<endl;
else }

throw zero(); Output:


Enter any number
} 0
terminate called after throwing an
instance of 'zero'
31
#include<iostream>
using namespace std;
class zero{};
void what_sign(int num) throw()
{
if (num>0)
cout<<"positive number"<<endl;
else if(num<0)
cout<<"negative number"<<endl;
else
throw zero();
}

32
void myunexpected()
{
cout<<"myunexpected invoked"<<endl;catch(...)
{
}
cout<<"Catch all
int main() Exceptions"<<endl;
{ }
cout<<"End of main()"<<endl;
int num;
}
cout<<"Enter any number"<<endl;
cin>>num;
set_unexpected(myunexpected); Output

try{ Enter any number


what_sign(num); 0
} myunexpected invoked

33

You might also like