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

Module V - Exceptions

1. Exceptions are errors that occur during runtime that are difficult to find during compilation like running out of memory or a user entering invalid data. 2. C++ uses exception handling to manage runtime errors using keywords try, catch, and throw. Code within a try block can throw an exception that is caught by a matching catch block. 3. Exceptions are objects that get passed from where the error occurs to where it is handled. The type of exception determines which catch block is used. Multiple catch blocks can be used to handle different exception types.

Uploaded by

SVS PRAVEEN
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Module V - Exceptions

1. Exceptions are errors that occur during runtime that are difficult to find during compilation like running out of memory or a user entering invalid data. 2. C++ uses exception handling to manage runtime errors using keywords try, catch, and throw. Code within a try block can throw an exception that is caught by a matching catch block. 3. Exceptions are objects that get passed from where the error occurs to where it is handled. The type of exception determines which catch block is used. Multiple catch blocks can be used to handle different exception types.

Uploaded by

SVS PRAVEEN
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Object Oriented Programming

using C++
Course Code: ES203
MODULE V-Exceptional Handling
Ms. Garima Srivastava
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow
Program Errors
• Kinds of errors with programs
– Logical error- Poor logic , bad algorithm
– Syntax Error- Improper syntax , bad implementation
• Exceptions - Unusual, but predictable problems, run time
anomalies that are difficult to find at compile time.
• The earlier you find an error, the less it costs to fix it.
• Modern compilers find errors early.

2
Exceptions
• You can fix poor logic (code reviews, debugger)
• You can fix improper syntax (asserts, debugger)
• You have to live with exceptions
– Run out of resources (memory, disk space)
– User enters bad data
– Floppy disk goes bad

3
Paradigm Shift from C
• In C, the default response to an error is to continue,
• possibly generating a message
• In C++, the default response to an error is to terminate
the
program
• C++ programs are more “brittle”, and you have to strive to
get them to work correctly
• Can catch all errors and continue as C does.

4
Why are Exceptions Needed?
• The types of problems which cause exceptions (running
out of resources, bad disk drive) are found at a low level
(say in a device driver)
• The low level code implementer does not know what your
application wants to do when the problem occurs, so s/he
“throws” the problem “up” to you.

5
How To Deal With Exceptions
• Crash the program
• Display a message and exit
• Display a message and allow the user to continue
• Correct the problem and continue without disturbing the
user.
• C++ provides a build-in error handling mechanism that is
called exception handling.
• Using exception handling, you can more easily manage
and respond to run-time errors .
6
What is a C++ Exception?
• An object
• – passed from the area where the problem occurs
• – passed to the area where the problem is handled
• The type of object determines which exception handler
will be used.
• C++ exception handling is built upon three keywords: try,
catch, and throw.

7
Mechanism
• Hit the exception
• Throw the exception
• Catch the exception
• Handle the exception

8
• In most general terms, 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).
• The exception is caught, using catch, and processed.
• The Code that you want to monitor for exceptions must
have been executed from within a try block.
• Functions called from within a try block may also throw an
• exception.
9
• Exceptions that can be thrown by the monitored code are caught
by a catch statement, which immediately follows the try statement
in which the exception was thrown.
• The general form of try and catch are shown here.
try {
// try block
}
catch (type1 arg) {
// catch block
}
10
catch (type2 arg) {
// catch block
}
catch (type3 arg) {
// catch block
}
..
catch (typeN arg) {
// catch block }
11
• There can be more than one catch statement associated
• with a try.
• Which catch statement is used is determined by the type
of the exception.
• That is, if the data type specified by a catch matches that
of the exception, then that catch statement is executed.
• When an exception is caught, arg will receive its value.
Any type of data may be caught, including classes that
you create.
12
• If no exception is thrown (that is, no error occurs within
the try block), then no catch statement is executed.
• The general form of the throw statement is shown here:
– throw exception;
• throw generates the exception specified by exception.
• If this exception is to be caught,then throw must be
executed either from within a try block itself, or from any
function called from within the try block (directly or
indirectly).
13
• If you throw an exception for which there is no applicable
catch statement an abnormal program termination may
occur.
• Throwing an unhandled exception causes the standard
library function terminate() to be invoked.
• By default, terminate() calls abort() to stop your program,
but you can specify your own termination handler also.

14
example
int main()
{cout << "Start\n";
try {
cout << "Inside try block\n";
throw 100; // throw an error
cout << "This will not execute";
}
catch (int i) {
cout << "Caught an exception -- value is: ";cout << i << "\n";
}
cout << "End";return 0;}

15
This program displays the following output:
Start
Inside try block
Caught an exception -- value is: 100
End

16
int main()
{
cout << "Start\n";
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: ";
17
cout << i << "\n";
}
cout << "End";
return 0;
}
This program produces the following output because the integer
exception will not be caught by the catch(double i) statement.
Start
Inside try block
Abnormal program termination

18
Throw Point
• 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.
void Xtest(int test)
{
cout << "Inside Xtest, test is: " << test << "\n";
if(test) throw test;
}
int main()
{
19
cout << "Start\n";
try { // start a try block
cout << "Inside try block\n";
Xtest(0);
Xtest(1);
Xtest(2);
}
catch (int i)
{ // catch an error
cout << "Caught an exception -- value is: ";
20
cout << i << "\n";
}
cout << "End";
return 0;
}
This program produces the following output:
Start
Inside try block
Inside Xtest, test is: 0
Inside Xtest, test is: 1
Caught an exception -- value is: 1
End
21
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.
void Xhandler(int test)
{
try{
if(test) throw test;
}
catch(int i) {

22
cout << "Caught Exception #: " << i << '\n';
}}
int main()
{cout << "Start\n";
Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);
cout << "End";
return 0;}
23
This program displays this output:
Start
Caught Exception #: 1
Caught Exception #: 2
Caught Exception #: 3
End
• As you can see, three exceptions are thrown. After each
exception, the function returns.
• When the function is called again, the exception handling
is reset.
24
Using Multiple catch Statements
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) {
25
cout << "Caught a string: ";
cout << str << '\n';
}}
int main()
{cout << "Start\n";
Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);
cout << "End";return 0;}
26
• This program produces the following output:
Start
Caught Exception #: 1
Caught Exception #: 2
Caught a string: Value is zero
Caught Exception #: 3
End

27
Catching All Exceptions
• In some circumstances you will want an exception
handler to catch all exceptions instead of just a certain
type.
• This is easy to accomplish.
• Simply use this form of catch.
catch(...) {
// process all exceptions
}
The ellipsis(…) matches any type of data.

28
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";
}}
29
int main()
{
cout << "Start\n";
Xhandler(0);
Xhandler(1);
Xhandler(2);
cout << "End";
return 0;
}

30
This program displays the following output.
Start
Caught One!
Caught One!
Caught One!
End
All three throws were caught using the one catch statement.
• One very good use for catch(...) is as the last catch of a cluster of
catches.
• In this capacity it provides a useful default or "catch all" statement.

31
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 integer\n";
}
32
catch(...) { // catch all other exceptions
cout << "Caught One!\n";
}}
int main()
{cout << "Start\n";
Xhandler(0);
Xhandler(1);
Xhandler(2);
cout << "End";
return 0;}

33
The output produced by this program is shown here.
Start
Caught an integer
Caught One!
Caught One!
End
As this example suggests, using catch(...) as a default is a good
way to catch all exceptions that you don't want to handle explicitly.
Also, by catching all exceptions, you prevent an unhandled
exception from causing an abnormal program termination.

34
Restricting Exceptions
• You can restrict the type of exceptions that a function can throw
outside of itself.
• In fact, 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)
{
// ...
}
35
• Only those data types contained in the comma-separated type-list
may be thrown by the function.
• 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.
36
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 << "start\n";

37
try{
Xhandler(0); // also, try passing 1 and 2 to Xhandler()
}
catch(int i) {
cout << "Caught an integer\n";
}
catch(char c) {
cout << "Caught char\n";
}
catch(double d) {
38
cout << "Caught double\n";
}
cout << "end";
return 0;
}

39
Rethrowing an Exception
• If you wish to rethrow an expression from within an
exception handler, you may do so by calling 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.
• For example, perhaps one exception handler manages
one aspect of an exception and a second handler copes
with another.
40
• 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 re caught
by the same catch statement.
• It will propagate outward to the next catch statement.

41
void Xhandler()
{
try {
throw "hello"; // throw a char *
}
catch(const char *) { // catch a char *
cout << "Caught char * inside Xhandler\n";
throw ; // rethrow char * out of function
}
}
42
int main()
{
cout << "Start\n";
try{
Xhandler();
}
catch(const char *) {
cout << "Caught char * inside main\n";
}
cout << "End";
return 0;
}
43
• This program displays this output:
Start
Caught char * inside Xhandler
Caught char * inside main
End

44
terminate( ) and 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.
• terminate() is the handler of last resort when no other
handlers for an exception are available.
• By default, terminate() calls abort() .

45
• 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() .
• By default,both functions halt program execution when an
exception handling error occurs.

46
Applying Exception Handling
void divide(double a, double b);
int main()
{
double i, j;
do {
cout << "Enter numerator (0 to stop): ";
cin >> i;
cout << "Enter denominator: ";
cin >> j;
divide(i, j);}
47
while(i != 0);
return 0;
}
void divide(double a, double b)
{
try {
if(!b) throw b; // check for divide-by-zero
cout << "Result: " << a/b << endl;
}
catch (double b)
48
{cout << "Can't divide by zero.\n"; }
}

49

You might also like