0% found this document useful (0 votes)
800 views

Exception Handling in C++

Exception handling allows programs to manage runtime errors in an orderly fashion by automatically invoking error handling routines when errors occur. The try block contains code that may throw exceptions, catch blocks catch specific exceptions, and exceptions are thrown using throw. Exception handling provides automated error handling through keywords like try, catch, and throw.

Uploaded by

yamuna
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
800 views

Exception Handling in C++

Exception handling allows programs to manage runtime errors in an orderly fashion by automatically invoking error handling routines when errors occur. The try block contains code that may throw exceptions, catch blocks catch specific exceptions, and exceptions are thrown using throw. Exception handling provides automated error handling through keywords like try, catch, and throw.

Uploaded by

yamuna
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 36

Exception handling

• Exception handling allows us to manage


run-time errors in an orderly fashion
• program can automatically invoke an
error-handling routine when an error
occurs.
• Advantage:
– Automation of error-handling code
Exception Handling Fundamentals
• three basic keywords: try, catch, and throw.
• program statements that you want to monitor for
exceptions are contained in a try block.
• If an exception (i.e., an error) occurs within the
try block, it is thrown (using throw).
• Functions called from within a try block may also
throw an exception.
• The exception is caught, using catch, and
processed.
Syntax
try { The syntax for throw statement is :
// try block
} throw exception
catch (type1 arg) {
// catch block
}
catch (type2 arg) {
// catch block
}
catch (type3 arg) {
// catch block
}
..
.
catch (typeN arg) {
// catch block
}
Handling Exceptions
• When an exception is thrown, it is caught
by its corresponding catch statement.
• There can be more than one catch
statement associated with a try.
• If the data type specified by a catch
matches that of the exception, then that
catch statement is executed (and all
others are bypassed).
Unhandled Exceptions
• If there is no applicable catch statement,
an abnormal program termination may
occur.
• For an unhandled exception, standard
library function terminate() is invoked.
• By default, terminate() calls abort() to
stop the program
Example: • Output:
#include <iostream>
using namespace std;
int main() Start
{ Inside try block
cout << "Start\n"; Caught an exception -- value is:
try { // start a try block 100
cout << "Inside try block\n"; End
throw 100; // throw an error
cout << "This will not execute";
}
catch (int i) { // catch an error
cout << "Caught an exception --
value is: ";
cout << i << "\n";
}
cout << "End";
}
• Once an exception has been thrown, control passes to the
catch expression and the try block is terminated.

• catch is not called. Rather, program execution is


transferred to it.

• The program's stack is automatically reset.

• The statements following the throw will never execute.

• If the error can be fixed, execution will continue after catch,


else a catch block will terminate the program with a call to
exit() or abort() .
The type of the exception must match the type specified in a catch
statement
The exception will not be caught and abnormal termination will
occur
#include <iostream> Output
using namespace std;
int main() Start
{ Inside try block
cout << "Start\n"; Abnormal program termination
try { // start a try block
cout << "Inside try block\n";
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;
}
Throwing an exception from a function outside the
try block.
#include <iostream> catch (int i) { // catch an error
using namespace std; cout << "Caught an exception -- value is: ";
cout << i << "\n";
void Xtest(int test) }
{ cout << "End";
cout << "Inside Xtest, test is: " << test << "\n"; return 0;
if(test) throw test; }
}
Output:
int main() Start
{ Inside try block
cout << "Start\n"; Inside Xtest, test is: 0
try { // start a try block Inside Xtest, test is: 1
cout << "Inside try block\n"; Caught an exception -- value is: 1
Xtest(0); End
Xtest(1);
Xtest(2);
}
Local try block
#include <iostream> Xhandler(2);
using namespace std; Xhandler(0);
// Localize a try/catch to a function. Xhandler(3);
void Xhandler(int test) cout << "End";
{ return 0;
try{ }
if(test) throw test;
} Output:
catch(int i) {
cout << "Caught Exception #: " << i << '\n'; Start
} Caught Exception #: 1
} Caught Exception #: 2
int main() Caught Exception #: 3
{ End
cout << "Start\n";
Xhandler(1);
Catching Class Types
• Generally an exception can be of any type.
• In real-world programs, most exceptions
will be class types rather than built-in
types.
• common reason - to create an object that
describes the error.
• It can be used by the exception handler to
help it process the error.
// Catching class type exceptions. catch (MyException e) { // catch an error
#include <iostream> cout << e.str_what << ": ";
#include <cstring>
using namespace std; cout << e.what << "\n";
class MyException { }
public: return 0;
char str_what[80]; }
int what;
MyException() { *str_what = 0; what = 0; }
MyException(char *s, int e) { Output:
strcpy(str_what, s);
what = e;
} Enter a positive number: -4
}; Not Positive: -4
int main()
{
int i;
try {
cout << "Enter a positive number: ";
cin >> i;
if(i<0)
throw MyException("Not Positive", i);
}
Using Multiple catch Statements
• There can be more than one catch
associated with a try.
• Each catch must catch a different type of
exception.
int main()
#include <iostream>
using namespace std; {
// Different types of exceptions can be cout << "Start\n";
caught. Xhandler(1);
void Xhandler(int test) Xhandler(2);
{ Xhandler(0);
Xhandler(3);
try{
if(test) throw test;
cout << "End";
else throw "Value is zero"; return 0;
} }

catch(int i) { Output:
cout << "Caught Exception #: " << i << '\n';
}
Start
catch(const char *str) { Caught Exception #: 1
cout << "Caught a string: "; Caught Exception #: 2
cout << str << '\n'; Caught a string: Value is zero
} Caught Exception #: 3
} End
Handling Derived-Class Exceptions
• order of catch statements is most
important while inheriting.
• because a catch clause for a base class
will also match any class derived from that
base.
• to catch exceptions of both a base class
and a derived class, put the derived class
first in the catch sequence.
// Catching derived classes. • In this example the catch clause of the
#include <iostream> base class will always be executed.
using namespace std;
class B { • reverse the order of the catch clauses
};
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;
}
Exception Handling Options
Additional features and nuances that make it
easier and more convenient to use are,
• Catching All Exceptions
• Restricting Exceptions
• Rethrowing an Exception
Catching All Exceptions
• This catch block will catch all kind of
exceptions
• Syntax:
catch(...) {
// process all exceptions
}
// This example catches all exceptions. int main()
#include <iostream> {
using namespace std; cout << "Start\n";
Xhandler(0);
void Xhandler(int test)
Xhandler(1);
{
Xhandler(2);
try{ cout << "End";
if(test==0) throw test; // throw int return 0;
if(test==1) throw 'a'; // throw char }
if(test==2) throw 123.23; // throw double
} Output:
Start
catch(...) { // catch all exceptions Caught One!
cout << "Caught One!\n"; Caught One!
} Caught One!
End
}
This block can be made the last catch block to catch all the
left out exceptions
// This example uses catch(...) as a int main()
default. {
#include <iostream> cout << "Start\n";
using namespace std; Xhandler(0);
void Xhandler(int test) Xhandler(1);
{ Xhandler(2);
try{ cout << "End";
if(test==0) throw test; // throw int return 0;
if(test==1) throw 'a'; // throw char }
if(test==2) throw 123.23; // throw double
} OUTPUT:
catch(int i) { // catch an int exception Start
cout << "Caught an integer\n";
Caught an integer
}
catch(...) { // catch all other exceptions
Caught One!
cout << "Caught One!\n"; Caught One!
} End
}
Restricting Exceptions
• Exceptions thrown outside the functions
can be restricted.
• To accomplish these restrictions, you must
add a throw clause to a function definition.
• Syntax:
ret-type func-name(arg-list) throw(type-list)
{
//..
}

• Only the types specified in the type-list can be thrown as


exceptions.
• Throwing any other type of expression will cause abnormal
program termination
• Attempting to throw an exception that is not supported by a function
will cause the standard library function unexpected() to be called
unexpected() -> abort()
// Restricting function throw types. catch(int i) {
#include <iostream> cout << "Caught an integer\n";
using namespace std; }

// This function can only throw ints, chars, catch(char c) {


and doubles. cout << "Caught char\n";
void Xhandler(int test) throw(int, char, }
double)
{
catch(double d) {
if(test==0) throw test; // throw int
cout << "Caught double\n";
if(test==1) throw 'a'; // throw char
}
if(test==2) throw 123.23; // throw double
cout << "end";
} return 0;
}
int main()
{
cout << "start\n";

try{
Xhandler(0); // also, try passing 1 and 2 to
Xhandler()
}
// This function can throw NO exceptions!
void Xhandler(int test) throw()
{
/* The following statements no longer work. Instead, they
will cause an abnormal program termination. */
if(test==0) throw test;
if(test==1) throw 'a';
if(test==2) throw 123.23;
}
Rethrowing an Exception
• An exception can be thrown back, by
calling throw, by itself, with no exception.
• the current exception to be passed on to
an outer try/catch sequence.
• This allows multiple handlers access to the
exception.
// Example of "rethrowing" an int main()
exception. {
#include <iostream> cout << "Start\n";
using namespace std; try{
void Xhandler() Xhandler();
{ }
catch(const char *) {
try { cout << "Caught char * inside
throw "hello"; // throw a char * main\n";
} }
cout << "End";
catch(const char *) { // catch a return 0;
char * }
cout << "Caught char * inside
Xhandler\n"; Output:
throw ; // rethrow char * out of Start
function
} Caught char * inside Xhandler
} Caught char * inside main
End
Understanding terminate() and unexpected()

• These functions are supplied by the


Standard C++ library
• These functions require the header
<exception>.
• Prototypes
– void terminate( );
– void unexpected( );
• The terminate() function is called whenever program
attempts to rethrow an exception when no exception was
originally thrown.

• Eg:
Unwinding the stack because of an exception, a
destructor for an object may throw an exception

• terminate() is the handler of last resort when no other


handlers for an exception are available.
terminate() -> abort()
• The unexpected() function is called when a
function attempts to throw an exception

• that is not allowed by its throw


unexpected() -> terminate() .
Setting the Terminate and Unexpected
Handlers
• Syntax:

terminate_handler set_terminate(terminate_handler newhandler) throw();

unexpected_handler set_unexpected(unexpected_handler newhandler) throw();

Both set_terminate() and set_unexpected() require the


header <exception>.
// Set a new terminate handler. Output:
#include <iostream>
#include <cstdlib> Inside try block
#include <exception> Inside new terminate handler
using namespace std; abnormal program termination
void my_Thandler() {
cout << "Inside new terminate handler\n";
abort();
}
int main()
{
// set a new terminate handler
set_terminate(my_Thandler);
try {
cout << "Inside try block\n";
throw 100; // throw an error
}
catch (double i) { // won't catch an int exception
// ...
}
return 0;
}
The uncaught_exception( ) Function

bool uncaught_exception( );

True -> if an exception has been thrown


but not yet caught.
False -> Exception is caught.
The exception and bad_exception Classes

• Exceptions thrown by C++ standard library will be object


derived from the base class exception.
• An object of the class bad_exception can be thrown by
the unexpected handler
• These classes require the header <exception.h>.
Applying Exception Handling
• Exception handling is designed to provide a
structured means to handle abnormal events.

• The error handler must do something rational


when an error occurs.
#include <iostream> void divide(double a, double b)
using namespace std; {
void divide(double a, double b);
int main() try {
{ if(!b) throw b; // check for divide-by-zero
double i, j; cout << "Result: " << a/b << endl;
do { }
cout << "Enter numerator (0 to
stop): "; catch (double b) {
cin >> i; cout << "Can't divide by zero.\n";
cout << "Enter denominator: "; }
cin >> j;
divide(i, j); }
} while(i != 0);
return 0;
}

You might also like