SlideShare a Scribd company logo
Chap 13
Exception handling
1 By:-Gourav Kottawar
Contents
13.1 Exception Handling Fundamentals
13.2 The try Block, the catch Exception Handler
13.3 The throw Statements
13.4 The try/throw/catch sequence
13.5 Exception Specification
13.6 Unexpected Exception
13.7 Catch – All Exception Handlers
13.8 Throwing an exception from handler
13.9 Uncaught Exception
2 By:-Gourav Kottawar
3
Syntax Errors, Runtime Errors, and Logic
Errors
three categories of errors:
syntax errors, runtime errors, and logic
errors.
Syntax errors arise because the rules of the
language have not been followed. They are
detected by the compiler.
 Runtime errors occur while the program is
running if the environment detects an operation
that is impossible to carry out.
Logic errors occur when a program doesn'tBy:-Gourav Kottawar
Introduction
 Allows to manage run time errors
 Using exception handling program can
invoke automatically invoke an error
handling routine when an error occurs.
 Automates error handling code.
4 By:-Gourav Kottawar
13.1 Exception Handling Fundamentals
 Based on three try , catch and throw
 Code that we want to monitor for exceptions must
have been executed from within try block.
 Functions called from try block may also throw an
exception.
 Exception that can be thrown by the monitored
code are caught by a catch statement.
5 By:-Gourav Kottawar
13.1 Exception Handling Fundamentals
 General syntax –
try
{
//try block
}catch(type1 args) {
//catch block
}
catch(type2 args) {
//catch block
}
catch(type3 args) {
//catch block
}
.
.
.
.
catch(typeN args) {
//catch block
}
General form of throw
throw exception
6 By:-Gourav Kottawar
#include<iostream.h>
#include<stdlib.h>
int main()
{
cout<<"n Startn";
try {
cout<<"Inside try
blockn";
throw 100;
cout<<"This will not
execute";
}
catch(int i)
{
cout<<"Caught exception
value is :";
cout<<i<<"n";
}
cout<<"n End";
return 0;
}7 By:-Gourav Kottawar
#include<iostream.h>
#include<stdlib.h>
int main()
{
cout<<"n Startn";
try {
cout<<"Inside try
blockn";
throw 100;
cout<<"This will not
execute";
}
catch(int i)
{
cout<<"Caught exception
value is :";
cout<<i<<"n";
}
cout<<"n End";
return 0;
}
//Output
Start
Inside try block
Caught exception value
is 100
End
8 By:-Gourav Kottawar
#include <iostream.h>
int main()
{
int StudentAge;
cout << "Student Age: ";
cin >> StudentAge;
try
{
if(StudentAge < 0)
throw;
cout << "nStudent Age: " << StudentAge << "nn";
}
catch(...)
{
}
cout << "n"; return 0;
}
9 By:-Gourav Kottawar
// This example will not work.
#include <iostream>
using namespace std;
int main()
{
cout << "Startn";
try { // start a try block
cout << "Inside try blockn";
throw 100; // throw an error
cout << "This will not execute";
}
catch (double i) { // won't work for an int
exception
cout << "Caught an exception -- value is: ";
cout << i << "n";
}
cout << "End";
return 0;
}
Start
Inside try block
Abnormal program
termination
10 By:-Gourav Kottawar
An exception can be thrown from outside the try block as long
as it is thrown by a function that is called from within try
block./* Throwing an exception from a
function outside the try block.
*/
#include <iostream>
using namespace std;
void Xtest(int test)
{
cout << "Inside Xtest, test is: " << test
<< "n";
if(test) throw test;
}
int main()
{
cout << "Startn";
try { // start a try block
cout << "Inside try blockn";
Xtest(0);
Xtest(1);
Xtest(2);
}
catch (int i) { // catch an error
cout << "Caught an exception --
value is: ";
cout << i << "n";
}
cout << "End";
return 0;
}
11 By:-Gourav Kottawar
An exception can be thrown from outside the try block as long
as it is thrown by a function that is called from within try
block./* Throwing an exception from a
function outside the try block.
*/
#include <iostream>
using namespace std;
void Xtest(int test)
{
cout << "Inside Xtest, test is: " << test
<< "n";
if(test) throw test;
}
int main()
{
cout << "Startn";
try { // start a try block
cout << "Inside try blockn";
Xtest(0);
Xtest(1);
Xtest(2);
}
catch (int i) { // catch an error
cout << "Caught an exception --
value is: ";
cout << i << "n";
}
cout << "End";
return 0;
} Start
Inside try block
Inside Xtest, test is: 0
Inside Xtest, test is: 1
Caught an exception -- value is: 1
End
12 By:-Gourav Kottawar
A try block can be localized to a function. When this is the case,
each time the function is entered, the exception handling relative to that
function is reset.
#include <iostream>
using namespace std;
// Localize a try/catch to a function.
void Xhandler(int test)
{
try{
if(test) throw test;
}
catch(int i) {
cout << "Caught Exception #: " << i <<
'n';
}
}
int main()
{
cout << "Startn";
Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);
cout << "End";
return 0;
}
13 By:-Gourav Kottawar
A try block can be localized to a function. When this is the case,
each time the function is entered, the exception handling relative to that
function is reset.
#include <iostream>
using namespace std;
// Localize a try/catch to a function.
void Xhandler(int test)
{
try{
if(test) throw test;
}
catch(int i) {
cout << "Caught Exception #: " << i <<
'n';
}
}
int main()
{
cout << "Startn";
Xhandler(1);
494 C + + : T h e C o m p l e
t e R e f e r e n c e
Xhandler(2);
Xhandler(0);
Xhandler(3);
cout << "End";
return 0;
}This program displays this
output:
Start
Caught Exception #: 1
Caught Exception #: 2
Caught Exception #: 314 By:-Gourav Kottawar
a catch statement will be executed only if it catches an exception. Otherwise,
execution simply bypasses the catch altogether.
#include <iostream.h>
int main()
{
cout << "Startn";
try { // start a try block
cout << "Inside try blockn";
cout << "Still inside try blockn";
}
catch (int i) { // catch an error
cout << "Caught an exception -- value is:
";
cout << i << "n";
}
C h a p t e r 1 9 : E x c e p t i o n H a n d l
i n g 495
cout << "End";
return 0;
}
Start
Inside try block
Still inside try block
End
the catch statement is bypassed by the flow of
execution
15 By:-Gourav Kottawar
Catching Class Types
 Exception can be of any type.
 Mostly it is user defined type. i.e. class
 the most common reason that you will want to
define a class type for an exception is to create
an object that describes the error that occurred.
This information can be used by the exception
handler to help it process the error.
16 By:-Gourav Kottawar
// Catching class type
exceptions.
#include <iostream.h>
#include <cstring.h>
class MyException {
public:
char str_what[80];
int what;
MyException()
{
*str_what = 0; what = 0;
}
MyException(char *s, int e)
{
strcpy(str_what, s);
what = e;
}
};
int main()
{
int i;
try {
cout << "Enter a positive number:
";
cin >> i;
if(i<0)
throw MyException("Not
Positive", i);
}
catch (MyException e) { // catch
an error
cout << e.str_what << ": ";
cout << e.what << "n";
}
return 0;
}
17 By:-Gourav Kottawar
// Catching class type
exceptions.
#include <iostream.h>
#include <cstring.h>
class MyException {
public:
char str_what[80];
int what;
MyException()
{
*str_what = 0; what = 0;
}
MyException(char *s, int e)
{
strcpy(str_what, s);
what = e;
}
};
int main()
{
int i;
try {
cout << "Enter a positive number:
";
cin >> i;
if(i<0)
throw MyException("Not
Positive", i);
}
catch (MyException e) { // catch
an error
cout << e.str_what << ": ";
cout << e.what << "n";
}
return 0;
}
Enter a positive number: -4
Not Positive: -4
18 By:-Gourav Kottawar
Using Multiple catch Statements
#include <iostream>
void Xhandler(int test)
{
try{
if(test) throw test;
else throw "Value is zero";
}
catch(int i) {
cout << "Caught Exception #: "
<< i << 'n';
}
catch(const char *str) {
cout << "Caught a string: ";
cout << str << 'n';
}
}
int main()
{
cout << "Startn";
Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);
cout << "End";
return 0;
}
19 By:-Gourav Kottawar
Using Multiple catch Statements
#include <iostream>
void Xhandler(int test)
{
try{
if(test) throw test;
else throw "Value is zero";
}
catch(int i) {
cout << "Caught Exception #: "
<< i << 'n';
}
catch(const char *str) {
cout << "Caught a string: ";
cout << str << 'n';
}
}
int main()
{
cout << "Startn";
Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);
cout << "End";
return 0;
}
Start
Caught Exception #: 1
Caught Exception #: 2
Caught a string: Value is zero
Caught Exception #: 3
End
20 By:-Gourav Kottawar
Handling Derived-Class Exceptions
// Catching derived
classes.
#include <iostream.h>
using namespace std;
class B
{
};
class D: public B
{
};
int main()
{
D derived;
try {
throw derived;
}
catch(B b) {
cout << "Caught a base
class.n";
}
catch(D d) {
cout << "This won't execute.n";
}
return 0;
}
21 By:-Gourav Kottawar
Catching All Exceptions
// This example catches all
exceptions.
#include <iostream.h>
void Xhandler(int test)
{
try{
if(test==0) throw test; // throw int
if(test==1) throw 'a'; // throw char
if(test==2) throw 123.23; // throw
double
}
catch(...) { // catch all exceptions
cout << "Caught One!n";
}
}
int main()
{
cout << "Startn";
Xhandler(0);
Xhandler(1);
Xhandler(2);
cout << "End";
return 0;
}
22 By:-Gourav Kottawar
Catching All Exceptions
// This example catches all
exceptions.
#include <iostream.h>
void Xhandler(int test)
{
try{
if(test==0) throw test; // throw int
if(test==1) throw 'a'; // throw char
if(test==2) throw 123.23; // throw
double
}
catch(...) { // catch all exceptions
cout << "Caught One!n";
}
}
int main()
{
cout << "Startn";
Xhandler(0);
Xhandler(1);
Xhandler(2);
cout << "End";
return 0;
}
//output
Start
Caught One!
Caught One!
Caught One!
End23 By:-Gourav Kottawar
// This example uses catch(...) as a
default.
#include <iostream.h>
void Xhandler(int test)
{
try{
if(test==0) throw test; // throw int
if(test==1) throw 'a'; // throw char
if(test==2) throw 123.23; // throw
double
}
catch(int i) { // catch an int
exception
cout << "Caught an integern";
}
catch(...) { // catch all other
exceptions
cout << "Caught One!n";
}
}
int main()
{
cout << "Startn";
Xhandler(0);
Xhandler(1);
Xhandler(2);
cout << "End";
return 0;
//output
Start
Caught an integer
Caught One!
Caught One!
End
24 By:-Gourav Kottawar
Restricting Exceptions
 You can restrict the type of exceptions that a function can
throw outside of itself.
 you can also prevent a function from throwing any
exceptions whatsoever.
 To accomplish these restrictions, you must add a throw
clause to a function definition.
 The general form of this is shown here:
ret-type func-name(arg-list) throw(type-list)
{
// ...
}
 only those data types contained in the comma-separated
type-list may be thrown by the function.
25 By:-Gourav Kottawar
 Throwing any other type of expression will cause
abnormal program
termination.
 If you don't want a function to be able to throw
any exceptions, then use an empty list.
 Attempting to throw an exception that is not
supported by a function will cause the standard
library function unexpected() to be called.
 By default, this causes abort() to be called, which
causes abnormal program termination.
26 By:-Gourav Kottawar
// Restricting function throw types.
#include <iostream.h>
// This function can only throw ints,
chars, and doubles.
void Xhandler(int test) throw(int, char,
double)
{
if(test==0) throw test; // throw int
if(test==1) throw 'a'; // throw char
if(test==2) throw 123.23; // throw double
}
int main()
{
cout << "startn";
try{
Xhandler(0); // also, try passing 1 and 2
to Xhandler()
}
catch(int i) {
cout << "Caught an integern";
}
catch(char c)
{
cout << "Caught charn";
}
catch(double d) {
cout << "Caught
doublen";
}
cout << "end";
return 0;
}
27 By:-Gourav Kottawar
Rethrowing an Exception
 We can rethrow exception using throw, by itself,
with no exception. This causes the current
exception to be passed on to an outer try/catch
sequence.
 The most likely reason for doing so is to allow
multiple handlers access to the exception.
 An exception can only be rethrown from within a
catch block (or from any function called from
within that block).
 When you rethrow an exception, it will not be
recaught by the same catch statement. It will
propagate outward to the next catch
statement.28 By:-Gourav Kottawar
#include <iostream.h>
void Xhandler()
{
try {
throw "hello"; // throw a
char *
}
catch(const char *) { //
catch a char *
cout << "Caught char *
inside Xhandlern";
throw ; // rethrow char * out
of function
}
}
int main()
{
cout << "Startn";
try{
Xhandler();
}
catch(const char *) {
cout << "Caught char * inside
mainn";
}
cout << "End";
return 0;
}
29 By:-Gourav Kottawar
#include <iostream.h>
void Xhandler()
{
try {
throw "hello"; // throw a
char *
}
catch(const char *) { //
catch a char *
cout << "Caught char *
inside Xhandlern";
throw ; // rethrow char * out
of function
}
}
int main()
{
cout << "Startn";
try{
Xhandler();
}
catch(const char *) {
cout << "Caught char * inside
mainn";
}
cout << "End";
return 0;
}//output
Start
Caught char * inside Xhandler
Caught char * inside main
End30 By:-Gourav Kottawar
Understanding terminate( ) and unexpected(
)
 terminate() and unexpected() are called when
something goes wrong during the exception
handling process.
These functions are supplied by the Standard C++
library.
 Their prototypes are shown here:
void terminate( );
void unexpected( );
 These functions require the header <exception>.
 The terminate() function is called whenever the
exception handling subsystem fails to find a
matching catch statement for an exception.
 It is also called if your program attempts to rethrow
an exception when no exception was originally
thrown.
31 By:-Gourav Kottawar
Understanding terminate( ) and unexpected( )
 The terminate() function is also called under
various other, more obscure circumstances.
 In general, terminate() is the handler of last
resort when no other handlers for an exception
are available. By default, terminate() calls
abort() .
 The unexpected() function is called when a
function attempts to throw an exception that is
not allowed by its throw list. By default,
unexpected() calls terminate() .
32 By:-Gourav Kottawar
Setting the Terminate and Unexpected Handlers
 The terminate() and unexpected() functions halt program
 execution when an exception handling error occurs. However,
you can change the functions that are called by terminate()
and unexpected() .
 program to take full control of the exception handling
subsystem.
 To change the terminate handler, use set_terminate()
terminate_handler set_terminate(terminate_handler newhandler)
throw( );
Here newhandler is a pointer to the new terminate handler. The
function returns a
pointer to the old terminate handler.
The new terminate handler must be of type terminate_handler,
which is defined like this:
typedef void (*terminate_handler) ( );
33 By:-Gourav Kottawar
To change the unexpected handler, use
set_unexpected() , shown here:
unexpected_handler
set_unexpected(unexpected_handler newhandler) throw( );
newhandler is a pointer to the new unexpected handler. The
function returns a
pointer to the old unexpected handler. The new unexpected
handler must be of type unexpected_handler, which is
defined like this:
typedef void (*unexpected_handler) ( );
This handler may itself throw an exception, stop the program, or
call terminate() .
However, it must not return to the program.
Both set_terminate() and set_unexpected() require the header
<exception>.
34 By:-Gourav Kottawar
#include <cstdlib>
#include <exception>
using namespace std;
void my_Thandler()
{
cout << "Inside new
terminate handlern";
abort();
}
int main()
{
// set a new terminate handler
set_terminate(my_Thandler);
try {
cout << "Inside try blockn";
throw 100; // throw an error
}
catch (double i) { // won't catch
an int exception
// ...
}
return 0;
}
35 By:-Gourav Kottawar
#include <cstdlib>
#include <exception>
using namespace std;
void my_Thandler()
{
cout << "Inside new
terminate handlern";
abort();
}
int main()
{
// set a new terminate handler
set_terminate(my_Thandler);
try {
cout << "Inside try blockn";
throw 100; // throw an error
}
catch (double i) { // won't catch
an int exception
// ...
}
return 0;
}
The output from this program
is shown here.
Inside try block
Inside new terminate handler
abnormal program termination36 By:-Gourav Kottawar
The uncaught_exception( ) Function
The C++ exception handling subsystem
supplies one other function that you may
finduseful: uncaught_exception() .
Its prototype is shown here:
bool uncaught_exception( );
This function returns true if an exception has
been thrown but not yet caught.
Once caught, the function returns false.
37 By:-Gourav Kottawar

More Related Content

PPTX
Inheritance in OOPs with java
PPTX
SHELL PROGRAMMING
PPT
Class 5 - PHP Strings
PDF
Ruby on Rails Presentation
PDF
Ruby on Rails Presentation
PPTX
Java input
PPT
Shell Scripting
PDF
Linux systems - Linux Commands and Shell Scripting
Inheritance in OOPs with java
SHELL PROGRAMMING
Class 5 - PHP Strings
Ruby on Rails Presentation
Ruby on Rails Presentation
Java input
Shell Scripting
Linux systems - Linux Commands and Shell Scripting

What's hot (20)

PPTX
Exception Handling in object oriented programming using C++
PPTX
Constructor and Types of Constructors
PPS
String and string buffer
PPTX
Exception handling
PPTX
Object oriented programming in java
PPT
Exception Handling in JAVA
PPTX
11. java methods
PPTX
Decision making and branching
PPT
C++ classes tutorials
PPTX
Java literals
PPTX
6. static keyword
PPTX
Php string function
PPTX
Java exception handling
PPTX
L14 exception handling
PPTX
Constructors & destructors
PDF
StringTokenizer in java
PPT
Lecture 2. MS SQL. Stored procedures.
PPT
Data structures using c
PPTX
array of object pointer in c++
PPTX
Socket programming in Java (PPTX)
Exception Handling in object oriented programming using C++
Constructor and Types of Constructors
String and string buffer
Exception handling
Object oriented programming in java
Exception Handling in JAVA
11. java methods
Decision making and branching
C++ classes tutorials
Java literals
6. static keyword
Php string function
Java exception handling
L14 exception handling
Constructors & destructors
StringTokenizer in java
Lecture 2. MS SQL. Stored procedures.
Data structures using c
array of object pointer in c++
Socket programming in Java (PPTX)
Ad

Viewers also liked (13)

PPTX
Exception handling
PPT
Exception handling in c++ by manoj vasava
PPSX
Exception Handling
PDF
Exception Handling in the C++ Constructor
PDF
Exception Handling
PPT
Exception handler
PPTX
Exception Handling in C++
PPTX
C++ ala
PDF
14 exception handling
PPTX
What is Exception Handling?
PPT
Exception handling
PPT
Exception handling and templates
PPS
Java Exception handling
Exception handling
Exception handling in c++ by manoj vasava
Exception Handling
Exception Handling in the C++ Constructor
Exception Handling
Exception handler
Exception Handling in C++
C++ ala
14 exception handling
What is Exception Handling?
Exception handling
Exception handling and templates
Java Exception handling
Ad

Similar to exception handling in cpp (20)

PPT
Exceptions in C++exception handling in C++, computer programming.ppt
PPTX
Object Oriented Programming Using C++: C++ Exception Handling.pptx
PPTX
15_exception_handling-1-exception handling .pptx
PDF
22 scheme OOPs with C++ BCS306B_module5.pdf
PPTX
Exception handling
PPT
Lecture16
PPTX
Lecture 09 Exception Handling(1 ) in c++.pptx
PPTX
Rethrowing exception- JAVA
PPTX
CAP444Unit6ExceptionHandling.pptx
PDF
Exceptions and Exception Handling in C++
PDF
Exception handling
PPTX
Project in programming
PPTX
Exception handling in java
PPT
Exception_Handling_in_C__1701342048430.ppt
PPTX
Unit II Java & J2EE regarding Java application development
PPTX
6-Exception Handling and Templates.pptx
PPTX
Exception handling
PDF
Chapter 3 Computer Programmingodp-1_250331_041044.pdf
PPTX
Exception handling in Java
PPTX
Exception handling
Exceptions in C++exception handling in C++, computer programming.ppt
Object Oriented Programming Using C++: C++ Exception Handling.pptx
15_exception_handling-1-exception handling .pptx
22 scheme OOPs with C++ BCS306B_module5.pdf
Exception handling
Lecture16
Lecture 09 Exception Handling(1 ) in c++.pptx
Rethrowing exception- JAVA
CAP444Unit6ExceptionHandling.pptx
Exceptions and Exception Handling in C++
Exception handling
Project in programming
Exception handling in java
Exception_Handling_in_C__1701342048430.ppt
Unit II Java & J2EE regarding Java application development
6-Exception Handling and Templates.pptx
Exception handling
Chapter 3 Computer Programmingodp-1_250331_041044.pdf
Exception handling in Java
Exception handling

More from gourav kottawar (20)

PPTX
operator overloading & type conversion in cpp
PPTX
constructor & destructor in cpp
PPTX
classes & objects in cpp
PPTX
expression in cpp
PPTX
basics of c++
PPT
working file handling in cpp overview
PPT
pointers, virtual functions and polymorphisms in c++ || in cpp
PPT
cpp input & output system basics
PPTX
operator overloading & type conversion in cpp over view || c++
PPTX
constructor & destructor in cpp
PPTX
basics of c++
PPTX
classes & objects in cpp overview
PPTX
expression in cpp
PPT
SQL || overview and detailed information about Sql
PPT
SQL querys in detail || Sql query slides
PPT
Rrelational algebra in dbms overview
PPT
overview of database concept
PPT
Relational Model in dbms & sql database
PPTX
DBMS information in detail || Dbms (lab) ppt
PPTX
security and privacy in dbms and in sql database
operator overloading & type conversion in cpp
constructor & destructor in cpp
classes & objects in cpp
expression in cpp
basics of c++
working file handling in cpp overview
pointers, virtual functions and polymorphisms in c++ || in cpp
cpp input & output system basics
operator overloading & type conversion in cpp over view || c++
constructor & destructor in cpp
basics of c++
classes & objects in cpp overview
expression in cpp
SQL || overview and detailed information about Sql
SQL querys in detail || Sql query slides
Rrelational algebra in dbms overview
overview of database concept
Relational Model in dbms & sql database
DBMS information in detail || Dbms (lab) ppt
security and privacy in dbms and in sql database

Recently uploaded (20)

PPTX
Cell Types and Its function , kingdom of life
PDF
Computing-Curriculum for Schools in Ghana
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
master seminar digital applications in india
PPTX
GDM (1) (1).pptx small presentation for students
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Complications of Minimal Access Surgery at WLH
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Cell Structure & Organelles in detailed.
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Basic Mud Logging Guide for educational purpose
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
Cell Types and Its function , kingdom of life
Computing-Curriculum for Schools in Ghana
O7-L3 Supply Chain Operations - ICLT Program
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
master seminar digital applications in india
GDM (1) (1).pptx small presentation for students
TR - Agricultural Crops Production NC III.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Complications of Minimal Access Surgery at WLH
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Abdominal Access Techniques with Prof. Dr. R K Mishra
human mycosis Human fungal infections are called human mycosis..pptx
Microbial disease of the cardiovascular and lymphatic systems
Cell Structure & Organelles in detailed.
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Basic Mud Logging Guide for educational purpose
STATICS OF THE RIGID BODIES Hibbelers.pdf

exception handling in cpp

  • 1. Chap 13 Exception handling 1 By:-Gourav Kottawar
  • 2. Contents 13.1 Exception Handling Fundamentals 13.2 The try Block, the catch Exception Handler 13.3 The throw Statements 13.4 The try/throw/catch sequence 13.5 Exception Specification 13.6 Unexpected Exception 13.7 Catch – All Exception Handlers 13.8 Throwing an exception from handler 13.9 Uncaught Exception 2 By:-Gourav Kottawar
  • 3. 3 Syntax Errors, Runtime Errors, and Logic Errors three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because the rules of the language have not been followed. They are detected by the compiler.  Runtime errors occur while the program is running if the environment detects an operation that is impossible to carry out. Logic errors occur when a program doesn'tBy:-Gourav Kottawar
  • 4. Introduction  Allows to manage run time errors  Using exception handling program can invoke automatically invoke an error handling routine when an error occurs.  Automates error handling code. 4 By:-Gourav Kottawar
  • 5. 13.1 Exception Handling Fundamentals  Based on three try , catch and throw  Code that we want to monitor for exceptions must have been executed from within try block.  Functions called from try block may also throw an exception.  Exception that can be thrown by the monitored code are caught by a catch statement. 5 By:-Gourav Kottawar
  • 6. 13.1 Exception Handling Fundamentals  General syntax – try { //try block }catch(type1 args) { //catch block } catch(type2 args) { //catch block } catch(type3 args) { //catch block } . . . . catch(typeN args) { //catch block } General form of throw throw exception 6 By:-Gourav Kottawar
  • 7. #include<iostream.h> #include<stdlib.h> int main() { cout<<"n Startn"; try { cout<<"Inside try blockn"; throw 100; cout<<"This will not execute"; } catch(int i) { cout<<"Caught exception value is :"; cout<<i<<"n"; } cout<<"n End"; return 0; }7 By:-Gourav Kottawar
  • 8. #include<iostream.h> #include<stdlib.h> int main() { cout<<"n Startn"; try { cout<<"Inside try blockn"; throw 100; cout<<"This will not execute"; } catch(int i) { cout<<"Caught exception value is :"; cout<<i<<"n"; } cout<<"n End"; return 0; } //Output Start Inside try block Caught exception value is 100 End 8 By:-Gourav Kottawar
  • 9. #include <iostream.h> int main() { int StudentAge; cout << "Student Age: "; cin >> StudentAge; try { if(StudentAge < 0) throw; cout << "nStudent Age: " << StudentAge << "nn"; } catch(...) { } cout << "n"; return 0; } 9 By:-Gourav Kottawar
  • 10. // This example will not work. #include <iostream> using namespace std; int main() { cout << "Startn"; try { // start a try block cout << "Inside try blockn"; throw 100; // throw an error cout << "This will not execute"; } catch (double i) { // won't work for an int exception cout << "Caught an exception -- value is: "; cout << i << "n"; } cout << "End"; return 0; } Start Inside try block Abnormal program termination 10 By:-Gourav Kottawar
  • 11. An exception can be thrown from outside the try block as long as it is thrown by a function that is called from within try block./* Throwing an exception from a function outside the try block. */ #include <iostream> using namespace std; void Xtest(int test) { cout << "Inside Xtest, test is: " << test << "n"; if(test) throw test; } int main() { cout << "Startn"; try { // start a try block cout << "Inside try blockn"; Xtest(0); Xtest(1); Xtest(2); } catch (int i) { // catch an error cout << "Caught an exception -- value is: "; cout << i << "n"; } cout << "End"; return 0; } 11 By:-Gourav Kottawar
  • 12. An exception can be thrown from outside the try block as long as it is thrown by a function that is called from within try block./* Throwing an exception from a function outside the try block. */ #include <iostream> using namespace std; void Xtest(int test) { cout << "Inside Xtest, test is: " << test << "n"; if(test) throw test; } int main() { cout << "Startn"; try { // start a try block cout << "Inside try blockn"; Xtest(0); Xtest(1); Xtest(2); } catch (int i) { // catch an error cout << "Caught an exception -- value is: "; cout << i << "n"; } cout << "End"; return 0; } Start Inside try block Inside Xtest, test is: 0 Inside Xtest, test is: 1 Caught an exception -- value is: 1 End 12 By:-Gourav Kottawar
  • 13. A try block can be localized to a function. When this is the case, each time the function is entered, the exception handling relative to that function is reset. #include <iostream> using namespace std; // Localize a try/catch to a function. void Xhandler(int test) { try{ if(test) throw test; } catch(int i) { cout << "Caught Exception #: " << i << 'n'; } } int main() { cout << "Startn"; Xhandler(1); Xhandler(2); Xhandler(0); Xhandler(3); cout << "End"; return 0; } 13 By:-Gourav Kottawar
  • 14. A try block can be localized to a function. When this is the case, each time the function is entered, the exception handling relative to that function is reset. #include <iostream> using namespace std; // Localize a try/catch to a function. void Xhandler(int test) { try{ if(test) throw test; } catch(int i) { cout << "Caught Exception #: " << i << 'n'; } } int main() { cout << "Startn"; Xhandler(1); 494 C + + : T h e C o m p l e t e R e f e r e n c e Xhandler(2); Xhandler(0); Xhandler(3); cout << "End"; return 0; }This program displays this output: Start Caught Exception #: 1 Caught Exception #: 2 Caught Exception #: 314 By:-Gourav Kottawar
  • 15. a catch statement will be executed only if it catches an exception. Otherwise, execution simply bypasses the catch altogether. #include <iostream.h> int main() { cout << "Startn"; try { // start a try block cout << "Inside try blockn"; cout << "Still inside try blockn"; } catch (int i) { // catch an error cout << "Caught an exception -- value is: "; cout << i << "n"; } C h a p t e r 1 9 : E x c e p t i o n H a n d l i n g 495 cout << "End"; return 0; } Start Inside try block Still inside try block End the catch statement is bypassed by the flow of execution 15 By:-Gourav Kottawar
  • 16. Catching Class Types  Exception can be of any type.  Mostly it is user defined type. i.e. class  the most common reason that you will want to define a class type for an exception is to create an object that describes the error that occurred. This information can be used by the exception handler to help it process the error. 16 By:-Gourav Kottawar
  • 17. // Catching class type exceptions. #include <iostream.h> #include <cstring.h> class MyException { public: char str_what[80]; int what; MyException() { *str_what = 0; what = 0; } MyException(char *s, int e) { strcpy(str_what, s); what = e; } }; int main() { int i; try { cout << "Enter a positive number: "; cin >> i; if(i<0) throw MyException("Not Positive", i); } catch (MyException e) { // catch an error cout << e.str_what << ": "; cout << e.what << "n"; } return 0; } 17 By:-Gourav Kottawar
  • 18. // Catching class type exceptions. #include <iostream.h> #include <cstring.h> class MyException { public: char str_what[80]; int what; MyException() { *str_what = 0; what = 0; } MyException(char *s, int e) { strcpy(str_what, s); what = e; } }; int main() { int i; try { cout << "Enter a positive number: "; cin >> i; if(i<0) throw MyException("Not Positive", i); } catch (MyException e) { // catch an error cout << e.str_what << ": "; cout << e.what << "n"; } return 0; } Enter a positive number: -4 Not Positive: -4 18 By:-Gourav Kottawar
  • 19. Using Multiple catch Statements #include <iostream> void Xhandler(int test) { try{ if(test) throw test; else throw "Value is zero"; } catch(int i) { cout << "Caught Exception #: " << i << 'n'; } catch(const char *str) { cout << "Caught a string: "; cout << str << 'n'; } } int main() { cout << "Startn"; Xhandler(1); Xhandler(2); Xhandler(0); Xhandler(3); cout << "End"; return 0; } 19 By:-Gourav Kottawar
  • 20. Using Multiple catch Statements #include <iostream> void Xhandler(int test) { try{ if(test) throw test; else throw "Value is zero"; } catch(int i) { cout << "Caught Exception #: " << i << 'n'; } catch(const char *str) { cout << "Caught a string: "; cout << str << 'n'; } } int main() { cout << "Startn"; Xhandler(1); Xhandler(2); Xhandler(0); Xhandler(3); cout << "End"; return 0; } Start Caught Exception #: 1 Caught Exception #: 2 Caught a string: Value is zero Caught Exception #: 3 End 20 By:-Gourav Kottawar
  • 21. Handling Derived-Class Exceptions // Catching derived classes. #include <iostream.h> using namespace std; class B { }; class D: public B { }; int main() { D derived; try { throw derived; } catch(B b) { cout << "Caught a base class.n"; } catch(D d) { cout << "This won't execute.n"; } return 0; } 21 By:-Gourav Kottawar
  • 22. Catching All Exceptions // This example catches all exceptions. #include <iostream.h> void Xhandler(int test) { try{ if(test==0) throw test; // throw int if(test==1) throw 'a'; // throw char if(test==2) throw 123.23; // throw double } catch(...) { // catch all exceptions cout << "Caught One!n"; } } int main() { cout << "Startn"; Xhandler(0); Xhandler(1); Xhandler(2); cout << "End"; return 0; } 22 By:-Gourav Kottawar
  • 23. Catching All Exceptions // This example catches all exceptions. #include <iostream.h> void Xhandler(int test) { try{ if(test==0) throw test; // throw int if(test==1) throw 'a'; // throw char if(test==2) throw 123.23; // throw double } catch(...) { // catch all exceptions cout << "Caught One!n"; } } int main() { cout << "Startn"; Xhandler(0); Xhandler(1); Xhandler(2); cout << "End"; return 0; } //output Start Caught One! Caught One! Caught One! End23 By:-Gourav Kottawar
  • 24. // This example uses catch(...) as a default. #include <iostream.h> void Xhandler(int test) { try{ if(test==0) throw test; // throw int if(test==1) throw 'a'; // throw char if(test==2) throw 123.23; // throw double } catch(int i) { // catch an int exception cout << "Caught an integern"; } catch(...) { // catch all other exceptions cout << "Caught One!n"; } } int main() { cout << "Startn"; Xhandler(0); Xhandler(1); Xhandler(2); cout << "End"; return 0; //output Start Caught an integer Caught One! Caught One! End 24 By:-Gourav Kottawar
  • 25. Restricting Exceptions  You can restrict the type of exceptions that a function can throw outside of itself.  you can also prevent a function from throwing any exceptions whatsoever.  To accomplish these restrictions, you must add a throw clause to a function definition.  The general form of this is shown here: ret-type func-name(arg-list) throw(type-list) { // ... }  only those data types contained in the comma-separated type-list may be thrown by the function. 25 By:-Gourav Kottawar
  • 26.  Throwing any other type of expression will cause abnormal program termination.  If you don't want a function to be able to throw any exceptions, then use an empty list.  Attempting to throw an exception that is not supported by a function will cause the standard library function unexpected() to be called.  By default, this causes abort() to be called, which causes abnormal program termination. 26 By:-Gourav Kottawar
  • 27. // Restricting function throw types. #include <iostream.h> // This function can only throw ints, chars, and doubles. void Xhandler(int test) throw(int, char, double) { if(test==0) throw test; // throw int if(test==1) throw 'a'; // throw char if(test==2) throw 123.23; // throw double } int main() { cout << "startn"; try{ Xhandler(0); // also, try passing 1 and 2 to Xhandler() } catch(int i) { cout << "Caught an integern"; } catch(char c) { cout << "Caught charn"; } catch(double d) { cout << "Caught doublen"; } cout << "end"; return 0; } 27 By:-Gourav Kottawar
  • 28. Rethrowing an Exception  We can rethrow exception using throw, by itself, with no exception. This causes the current exception to be passed on to an outer try/catch sequence.  The most likely reason for doing so is to allow multiple handlers access to the exception.  An exception can only be rethrown from within a catch block (or from any function called from within that block).  When you rethrow an exception, it will not be recaught by the same catch statement. It will propagate outward to the next catch statement.28 By:-Gourav Kottawar
  • 29. #include <iostream.h> void Xhandler() { try { throw "hello"; // throw a char * } catch(const char *) { // catch a char * cout << "Caught char * inside Xhandlern"; throw ; // rethrow char * out of function } } int main() { cout << "Startn"; try{ Xhandler(); } catch(const char *) { cout << "Caught char * inside mainn"; } cout << "End"; return 0; } 29 By:-Gourav Kottawar
  • 30. #include <iostream.h> void Xhandler() { try { throw "hello"; // throw a char * } catch(const char *) { // catch a char * cout << "Caught char * inside Xhandlern"; throw ; // rethrow char * out of function } } int main() { cout << "Startn"; try{ Xhandler(); } catch(const char *) { cout << "Caught char * inside mainn"; } cout << "End"; return 0; }//output Start Caught char * inside Xhandler Caught char * inside main End30 By:-Gourav Kottawar
  • 31. Understanding terminate( ) and unexpected( )  terminate() and unexpected() are called when something goes wrong during the exception handling process. These functions are supplied by the Standard C++ library.  Their prototypes are shown here: void terminate( ); void unexpected( );  These functions require the header <exception>.  The terminate() function is called whenever the exception handling subsystem fails to find a matching catch statement for an exception.  It is also called if your program attempts to rethrow an exception when no exception was originally thrown. 31 By:-Gourav Kottawar
  • 32. Understanding terminate( ) and unexpected( )  The terminate() function is also called under various other, more obscure circumstances.  In general, terminate() is the handler of last resort when no other handlers for an exception are available. By default, terminate() calls abort() .  The unexpected() function is called when a function attempts to throw an exception that is not allowed by its throw list. By default, unexpected() calls terminate() . 32 By:-Gourav Kottawar
  • 33. Setting the Terminate and Unexpected Handlers  The terminate() and unexpected() functions halt program  execution when an exception handling error occurs. However, you can change the functions that are called by terminate() and unexpected() .  program to take full control of the exception handling subsystem.  To change the terminate handler, use set_terminate() terminate_handler set_terminate(terminate_handler newhandler) throw( ); Here newhandler is a pointer to the new terminate handler. The function returns a pointer to the old terminate handler. The new terminate handler must be of type terminate_handler, which is defined like this: typedef void (*terminate_handler) ( ); 33 By:-Gourav Kottawar
  • 34. To change the unexpected handler, use set_unexpected() , shown here: unexpected_handler set_unexpected(unexpected_handler newhandler) throw( ); newhandler is a pointer to the new unexpected handler. The function returns a pointer to the old unexpected handler. The new unexpected handler must be of type unexpected_handler, which is defined like this: typedef void (*unexpected_handler) ( ); This handler may itself throw an exception, stop the program, or call terminate() . However, it must not return to the program. Both set_terminate() and set_unexpected() require the header <exception>. 34 By:-Gourav Kottawar
  • 35. #include <cstdlib> #include <exception> using namespace std; void my_Thandler() { cout << "Inside new terminate handlern"; abort(); } int main() { // set a new terminate handler set_terminate(my_Thandler); try { cout << "Inside try blockn"; throw 100; // throw an error } catch (double i) { // won't catch an int exception // ... } return 0; } 35 By:-Gourav Kottawar
  • 36. #include <cstdlib> #include <exception> using namespace std; void my_Thandler() { cout << "Inside new terminate handlern"; abort(); } int main() { // set a new terminate handler set_terminate(my_Thandler); try { cout << "Inside try blockn"; throw 100; // throw an error } catch (double i) { // won't catch an int exception // ... } return 0; } The output from this program is shown here. Inside try block Inside new terminate handler abnormal program termination36 By:-Gourav Kottawar
  • 37. The uncaught_exception( ) Function The C++ exception handling subsystem supplies one other function that you may finduseful: uncaught_exception() . Its prototype is shown here: bool uncaught_exception( ); This function returns true if an exception has been thrown but not yet caught. Once caught, the function returns false. 37 By:-Gourav Kottawar