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

What's hot

Functions in javascript
Functions in javascriptFunctions in javascript
Introduction to xml
Introduction to xmlIntroduction to xml
Introduction to xml
Gtu Booker
 
Friends function and_classes
Friends function and_classesFriends function and_classes
Friends function and_classesasadsardar
 
Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
chathuranga kasun bamunusingha
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
Eyal Vardi
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
Mindy McAdams
 
JavaScript: Events Handling
JavaScript: Events HandlingJavaScript: Events Handling
JavaScript: Events Handling
Yuriy Bezgachnyuk
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
WebStackAcademy
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.ppt
Varshini62
 
IMPLEMENTATION OF AUTO KEY IN C++
IMPLEMENTATION OF AUTO KEY IN C++IMPLEMENTATION OF AUTO KEY IN C++
IMPLEMENTATION OF AUTO KEY IN C++
Sanjay Kumar Chakravarti
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++
Janki Shah
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#
Rizwan Ali
 
Threads in JAVA
Threads in JAVAThreads in JAVA
PHP variables
PHP  variablesPHP  variables
PHP variables
Siddique Ibrahim
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Datatype in JavaScript
Datatype in JavaScriptDatatype in JavaScript
Datatype in JavaScript
Rajat Saxena
 
Regular expression in javascript
Regular expression in javascriptRegular expression in javascript
Regular expression in javascript
Toan Nguyen
 
Abstraction in c++ and Real Life Example of Abstraction in C++
Abstraction in c++ and Real Life Example of Abstraction in C++Abstraction in c++ and Real Life Example of Abstraction in C++
Abstraction in c++ and Real Life Example of Abstraction in C++
Hitesh Kumar
 
Wrapper class
Wrapper classWrapper class
Wrapper class
kamal kotecha
 

What's hot (20)

Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
Introduction to xml
Introduction to xmlIntroduction to xml
Introduction to xml
 
Friends function and_classes
Friends function and_classesFriends function and_classes
Friends function and_classes
 
Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
 
JavaScript: Events Handling
JavaScript: Events HandlingJavaScript: Events Handling
JavaScript: Events Handling
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.ppt
 
IMPLEMENTATION OF AUTO KEY IN C++
IMPLEMENTATION OF AUTO KEY IN C++IMPLEMENTATION OF AUTO KEY IN C++
IMPLEMENTATION OF AUTO KEY IN C++
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Datatype in JavaScript
Datatype in JavaScriptDatatype in JavaScript
Datatype in JavaScript
 
Regular expression in javascript
Regular expression in javascriptRegular expression in javascript
Regular expression in javascript
 
Abstraction in c++ and Real Life Example of Abstraction in C++
Abstraction in c++ and Real Life Example of Abstraction in C++Abstraction in c++ and Real Life Example of Abstraction in C++
Abstraction in c++ and Real Life Example of Abstraction in C++
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 

Viewers also liked

Exception handling
Exception handlingException handling
Exception handling
Abhishek Pachisia
 
Exception handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaException handling in c++ by manoj vasava
Exception handling in c++ by manoj vasava
Manoj_vasava
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
Somenath Mukhopadhyay
 
Exception Handling
Exception HandlingException Handling
Exception HandlingAlpesh Oza
 
Exception handler
Exception handler Exception handler
Exception handler dishni
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
Deepak Tathe
 
C++ ala
C++ alaC++ ala
C++ ala
Megha Patel
 
14 exception handling
14 exception handling14 exception handling
14 exception handlingjigeno
 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
Syed Bahadur Shah
 
Exception handling
Exception handlingException handling
Exception handling
Prafull Johri
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templatesfarhan amjad
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 

Viewers also liked (13)

Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaException handling in c++ by manoj vasava
Exception handling in c++ by manoj vasava
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handler
Exception handler Exception handler
Exception handler
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
 
C++ ala
C++ alaC++ ala
C++ ala
 
14 exception handling
14 exception handling14 exception handling
14 exception handling
 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 

Similar to exception handling in cpp

Object Oriented Programming Using C++: C++ Exception Handling.pptx
Object Oriented Programming Using C++: C++ Exception Handling.pptxObject Oriented Programming Using C++: C++ Exception Handling.pptx
Object Oriented Programming Using C++: C++ Exception Handling.pptx
RashidFaridChishti
 
Exception handling
Exception handlingException handling
Exception handling
Waqas Abbasi
 
Lecture 09 Exception Handling(1 ) in c++.pptx
Lecture 09 Exception Handling(1 ) in c++.pptxLecture 09 Exception Handling(1 ) in c++.pptx
Lecture 09 Exception Handling(1 ) in c++.pptx
ZenLooper
 
Rethrowing exception- JAVA
Rethrowing exception- JAVARethrowing exception- JAVA
Rethrowing exception- JAVA
Rajan Shah
 
CAP444Unit6ExceptionHandling.pptx
CAP444Unit6ExceptionHandling.pptxCAP444Unit6ExceptionHandling.pptx
CAP444Unit6ExceptionHandling.pptx
SatyajeetGaur2
 
Exceptions and Exception Handling in C++
Exceptions and Exception Handling in C++Exceptions and Exception Handling in C++
Exceptions and Exception Handling in C++
IRJET Journal
 
Exception handling
Exception handlingException handling
Exception handling
Pranali Chaudhari
 
Project in programming
Project in programmingProject in programming
Project in programming
sahashi11342091
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
yugandhar vadlamudi
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptx6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptx
SatyamMishra237306
 
Exception handling
Exception handlingException handling
Exception handling
zindadili
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in JavaPrasad Sawant
 
Exception handling
Exception handlingException handling
Exception handling
SAIFUR RAHMAN
 
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptxWINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
ssusercd11c4
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
Open Gurukul
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
Jayant Dalvi
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2rohassanie
 
Exception handling
Exception handlingException handling
Exception handlingIblesoft
 

Similar to exception handling in cpp (20)

Object Oriented Programming Using C++: C++ Exception Handling.pptx
Object Oriented Programming Using C++: C++ Exception Handling.pptxObject Oriented Programming Using C++: C++ Exception Handling.pptx
Object Oriented Programming Using C++: C++ Exception Handling.pptx
 
Exception handling
Exception handlingException handling
Exception handling
 
Lecture16
Lecture16Lecture16
Lecture16
 
Lecture 09 Exception Handling(1 ) in c++.pptx
Lecture 09 Exception Handling(1 ) in c++.pptxLecture 09 Exception Handling(1 ) in c++.pptx
Lecture 09 Exception Handling(1 ) in c++.pptx
 
Rethrowing exception- JAVA
Rethrowing exception- JAVARethrowing exception- JAVA
Rethrowing exception- JAVA
 
CAP444Unit6ExceptionHandling.pptx
CAP444Unit6ExceptionHandling.pptxCAP444Unit6ExceptionHandling.pptx
CAP444Unit6ExceptionHandling.pptx
 
Exceptions and Exception Handling in C++
Exceptions and Exception Handling in C++Exceptions and Exception Handling in C++
Exceptions and Exception Handling in C++
 
Exception handling
Exception handlingException handling
Exception handling
 
Project in programming
Project in programmingProject in programming
Project in programming
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
 
6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptx6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptx
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exception handling
Exception handlingException handling
Exception handling
 
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptxWINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
Exception handling
Exception handlingException handling
Exception handling
 

More from gourav kottawar

operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cpp
gourav kottawar
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
gourav kottawar
 
classes & objects in cpp
classes & objects in cppclasses & objects in cpp
classes & objects in cpp
gourav kottawar
 
expression in cpp
expression in cppexpression in cpp
expression in cpp
gourav kottawar
 
basics of c++
basics of c++basics of c++
basics of c++
gourav kottawar
 
working file handling in cpp overview
working file handling in cpp overviewworking file handling in cpp overview
working file handling in cpp overview
gourav kottawar
 
pointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpppointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpp
gourav kottawar
 
cpp input & output system basics
cpp input & output system basicscpp input & output system basics
cpp input & output system basics
gourav kottawar
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
gourav kottawar
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
gourav kottawar
 
basics of c++
basics of c++basics of c++
basics of c++
gourav kottawar
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
gourav kottawar
 
expression in cpp
expression in cppexpression in cpp
expression in cpp
gourav kottawar
 
SQL || overview and detailed information about Sql
SQL || overview and detailed information about SqlSQL || overview and detailed information about Sql
SQL || overview and detailed information about Sql
gourav kottawar
 
SQL querys in detail || Sql query slides
SQL querys in detail || Sql query slidesSQL querys in detail || Sql query slides
SQL querys in detail || Sql query slides
gourav kottawar
 
Rrelational algebra in dbms overview
Rrelational algebra in dbms overviewRrelational algebra in dbms overview
Rrelational algebra in dbms overview
gourav kottawar
 
overview of database concept
overview of database conceptoverview of database concept
overview of database concept
gourav kottawar
 
Relational Model in dbms & sql database
Relational Model in dbms & sql databaseRelational Model in dbms & sql database
Relational Model in dbms & sql database
gourav kottawar
 
DBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptDBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) ppt
gourav kottawar
 
security and privacy in dbms and in sql database
security and privacy in dbms and in sql databasesecurity and privacy in dbms and in sql database
security and privacy in dbms and in sql database
gourav kottawar
 

More from gourav kottawar (20)

operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cpp
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
 
classes & objects in cpp
classes & objects in cppclasses & objects in cpp
classes & objects in cpp
 
expression in cpp
expression in cppexpression in cpp
expression in cpp
 
basics of c++
basics of c++basics of c++
basics of c++
 
working file handling in cpp overview
working file handling in cpp overviewworking file handling in cpp overview
working file handling in cpp overview
 
pointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpppointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpp
 
cpp input & output system basics
cpp input & output system basicscpp input & output system basics
cpp input & output system basics
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
 
basics of c++
basics of c++basics of c++
basics of c++
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
 
expression in cpp
expression in cppexpression in cpp
expression in cpp
 
SQL || overview and detailed information about Sql
SQL || overview and detailed information about SqlSQL || overview and detailed information about Sql
SQL || overview and detailed information about Sql
 
SQL querys in detail || Sql query slides
SQL querys in detail || Sql query slidesSQL querys in detail || Sql query slides
SQL querys in detail || Sql query slides
 
Rrelational algebra in dbms overview
Rrelational algebra in dbms overviewRrelational algebra in dbms overview
Rrelational algebra in dbms overview
 
overview of database concept
overview of database conceptoverview of database concept
overview of database concept
 
Relational Model in dbms & sql database
Relational Model in dbms & sql databaseRelational Model in dbms & sql database
Relational Model in dbms & sql database
 
DBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptDBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) ppt
 
security and privacy in dbms and in sql database
security and privacy in dbms and in sql databasesecurity and privacy in dbms and in sql database
security and privacy in dbms and in sql database
 

Recently uploaded

Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 

Recently uploaded (20)

Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 

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