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

Week9_ExceptionHandling

The document provides an overview of exception handling in C++, explaining how exceptions indicate problems during program execution and how they can be managed to enhance program robustness. It details the fundamental concepts of try, throw, and catch blocks, as well as the structure of exception classes and the process of throwing and catching exceptions. Additionally, it includes examples and references for further reading on the topic.

Uploaded by

surendran.phd.it
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Week9_ExceptionHandling

The document provides an overview of exception handling in C++, explaining how exceptions indicate problems during program execution and how they can be managed to enhance program robustness. It details the fundamental concepts of try, throw, and catch blocks, as well as the structure of exception classes and the process of throwing and catching exceptions. Additionally, it includes examples and references for further reading on the topic.

Uploaded by

surendran.phd.it
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 25

WEEK 9

HANDLING EXCEPTIONS IN C+
+
Dr.Surendran,
Assistant Professor,
College of Computer Studies

 2006 Pearson Education, Inc. All rights reserved.


Exception Handling in C++ 2

Introduction
• Exceptions
• Indicate problems that occur during a program’s
execution
• Occur infrequently
• Exception handling
• Can resolve exceptions
• Allow a program to continue executing or
• Notify the user of the problem and
• Terminate the program in a controlled manner
• Makes programs robust and fault-tolerant

 2006 Pearson Education, Inc. All rights reserved.


Exception Handling in C++ 3

Fundamental Philosophy
• Programs can
• Recover from exceptions
• Hide exceptions
• Pass exceptions up the “chain of
command”
• Ignore certain exceptions and let
someone else handle them

 2006 Pearson Education, Inc. All rights reserved.


Exception Handling in C++ 4

Fundamental Philosophy (continued)


• An exception is a class
• Usually derived from one of the system’s
exception base classes
• If an exceptional or error situation occurs,
program throws an object of that class

• A calling program can choose to catch exceptions


of certain classes
• Take action based on the exception object

 2006 Pearson Education, Inc. All rights reserved.


Basics of C++ Exception Handling: try, throw,
catch

• A function can throw an exception object if it


detects an error
• Object typically a character string (error message) or
class object
• If exception handler exists, exception caught and handled
• Otherwise, program terminates

 2006 Pearson Education, Inc. All rights reserved.


Basics of C++ Exception Handling: try,
throw, catch (II)

• Format
• Enclose code that may have an error in try block
• Follow with one or more catch blocks
• Each catch block has an exception handler
• If exception occurs and matches parameter in catch
block, code in catch block executed
• If no exception thrown, exception handlers skipped and
control resumes after catch blocks
• throw point - place where exception occurred
• Control cannot return to throw point

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig27_02.cpp Exception Handling in C++ 7
2
3
// A simple exception-handling example that checks for
// divide-by-zero exceptions. Zero Divide
4 #include <iostream.h>
5
6
using std::cin;
using std::cout;
Example
7 using std::endl;
8
9 #include "DivideByZeroException.h" // DivideByZeroException class
10
11 // perform division and throw DivideByZeroException object if
12 // divide-by-zero exception occurs
13 double quotient( int numerator, int denominator )
14 {
15 // throw DivideByZeroException if trying to divide by zero
16 if ( denominator == 0 )
17 throw DivideByZeroException(); // terminate function
18
19 // return division result
20 return static_cast< double >( numerator ) / denominator;
21 } // end function quotient
22
23 int main()
24 {
25 int number1; // user-specified numerator
26 int number2; // user-specified denominator
27 double result; // result of division
28
29 cout << "Enter two integers (end-of-file to end): ";

 2006 Pearson Education, Inc. All rights reserved.


Exception Handling in C++ 8

30 Zero Divide
31 // enable user to enter two integers to divide
32
33
while ( cin >> number1 >> number2 )
{
Example
34 // try block contains code that might throw exception
35 // and code that should not execute if an exception occurs
36 try
37 {
38 result = quotient( number1, number2 );
39 cout << "The quotient is: " << result << endl;
40 } // end try
41
42 // exception handler handles a divide-by-zero exception
43 catch ( DivideByZeroException &divideByZeroException )
44 {
45 cout << "Exception occurred: "
46 << divideByZeroException.what() << endl;
47 } // end catch
48
49 cout << "\nEnter two integers (end-of-file to end): ";
50 } // end while
51
52 cout << endl;
53 return 0; // terminate normally
54 } // end main

 2006 Pearson Education, Inc. All rights reserved.


Exception Handling in C++ 9

try Blocks
• Keyword try followed by braces ({})
• Should enclose
• Statements that might cause exceptions
• Statements that should be skipped in case of an exception

 2006 Pearson Education, Inc. All rights reserved.


Exception Handling in C++ 10

Catch Handlers
• Immediately follow a try block
• One or more catch handlers for each try block
• Keyword catch
• Exception parameter enclosed in parentheses
• Represents the type of exception to process
• Can provide an optional parameter name to interact with
the caught exception object
• Executes if exception parameter type matches
the exception thrown in the try block
• Could be a base class of the thrown exception’s class

 2006 Pearson Education, Inc. All rights reserved.


Exception Handling in C++ 11

Catch Handlers (continued)


try { All other classes of exceptions
// code to try are not handled here
}
catch (exceptionClass1 &name1) {
// handle exceptions of exceptionClass1
}
catch (exceptionClass2 &name2) {
// handle exceptions of exceptionClass2
}
catch (exceptionClass3 &name3) {
// handle exceptions of exceptionClass3
}
... catch clauses attempted
/* code to execute if in order; first match wins!
no exception or
catch handler handled exception*/

 2006 Pearson Education, Inc. All rights reserved.


Exception Handling in C++ 12

Throwing an Exception
• Use keyword throw followed by an operand
representing the type of exception
• The throw operand can be of any type
• If the throw operand is an object, it is called an exception
object
• The throw operand initializes the exception parameter
in the matching catch handler, if one is found

 2006 Pearson Education, Inc. All rights reserved.


Exception Handling in C++ 13

Exception Specifications
• Also called throw lists
• Keyword throw
• Comma-separated list of exception classes in
parentheses
Optional!
• Example
• int someFunction( double value )
throw ( ExceptionA, ExceptionB,
ExceptionC )
{
...
}
• Indicates someFunction can throw types
ExceptionA, ExceptionB and ExceptionC

 2006 Pearson Education, Inc. All rights reserved.


Exception Handling in C++ 14

Error Note
• The compiler will not generate a compilation error
if a function contains a throw expression for an
exception not listed in the function’s exception
specification.
• Error occurs only when that function attempts to
throw that exception at run time.
• To avoid surprises at execution time, carefully
check your code to ensure that functions do not
throw exceptions not listed in their exception
specifications

 2006 Pearson Education, Inc. All rights reserved.


Exception Handling in C++ 15

Standard Library exception classes.

 2006 Pearson Education, Inc. All rights reserved.


Try and Catch
• Using Function A from the previous slide, here
is how to catch MyException:
void functionB( )
{

try
{

functionA( );

}
catch(MyException e)
{
< handle the exception>
}
}

 2006 Pearson Education, Inc. All rights reserved.


The try Block
• if-else statement with
if(milk <= 0)
throw donuts;
• This code is found in the try block
try
{
Some_Code
}

which encloses the code to handle the normal


situations

 2006 Pearson Education, Inc. All rights reserved.


The Exception
• To throw an exception, a throw-statement is
used to throw a value
• In the milk example:
throw donuts;
throws an integer value.
• The value thrown is sometimes called an exception
• You can throw a value of any type

 2006 Pearson Education, Inc. All rights reserved.


The catch-block
• Something that is thrown goes from one place
to another
• In C++ throw causes the flow of control to go
to another place
• When an exception is thrown, the try block stops
executing and the catch-block begins execution
• This is catching or handling the exception

 2006 Pearson Education, Inc. All rights reserved.


The Milk catch-block
• The catch-block from the milk example looks
like, but is not, a function definition with a
parameter:
catch(int e)
{
cout << e << donuts, and no milk!\n"
<< "Go buy some milk.\n";
}
• If no exception is thrown, the catch-block is ignored
during program execution

 2006 Pearson Education, Inc. All rights reserved.


Exception Handling in C++

 2006 Pearson Education, Inc. All rights reserved.


 2006 Pearson Education, Inc. All rights reserved.
Outline
Enter two integers (end-of-file to end): 100 7
The quotient is: 14.2857

Enter two integers (end-of-file to end): 100 0


Exception occurred: attempted to divide by zero

Enter two integers (end-of-file to end): 33 9


The quotient is: 3.66667

Enter two integers (end-of-file to end):

 2000 Prentice Hall, Inc. All


CS655

Paul F. Reynolds, Jr.

Exception Hierarchies
class Matherr { };
class Overflow: public Matherr { };
class Underflow: public Matherr { };
class Zerodivide: public Matherr { };
//…
void g { }
{
try {
f();
}
catch (Overflow) { } // handle overflow, derived exceptions
catch (Matherr) { } // handle any Matherr that’s not
overflow
}

 2006 Pearson Education, Inc. All rights reserved.


References
• The C++ Programming Language, 3rd Edition, Stroustrup, Addison-
Wesley, 1997

• Exceptional C++, Sutter, Addison- Wesley, 2000

• There is a very nice summary in our text:


The C++ Standard Library, Nicolai Josuttis, Addison Wesley, 1999

 2006 Pearson Education, Inc. All rights reserved.

You might also like