Upload
tristan-newman
View
214
Download
0
Embed Size (px)
Citation preview
Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Chapter 16Chapter 16Exception HandlingException Handling
Slide 16- 2
OverviewOverview
16.1 Exception-Handling Basics16.1 Exception-Handling Basics
16.2 Programming Techniques for 16.2 Programming Techniques for
Exception Handling Exception Handling
Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
16.116.1Exception-Handling BasicsException-Handling Basics
Slide 16- 4
Exception Handling BasicsException Handling Basics
It is often easier to write a program by firstIt is often easier to write a program by firstassuming that nothing incorrect will happenassuming that nothing incorrect will happen
Once it works correctly for the expected Once it works correctly for the expected cases, add code to handle the exceptional cases, add code to handle the exceptional casescases
Exception handling is commonly used to Exception handling is commonly used to handle error situationshandle error situations Once an error is handled, it is no longer an Once an error is handled, it is no longer an
errorerror
Slide 16- 5
Functions and Functions and Exception HandlingException Handling
A common use of exception handling:A common use of exception handling: Functions with a special case that is Functions with a special case that is
handled in different ways depending on handled in different ways depending on how the function is usedhow the function is used
If the function is used in different If the function is used in different programs, each program may require a programs, each program may require a different action when the special case different action when the special case occurs occurs
Slide 16- 6
Exception Handling MechanismException Handling Mechanism
In C++, exception handling proceeds by:In C++, exception handling proceeds by: Some library software or your code signals Some library software or your code signals
that something unusual has happenedthat something unusual has happened This is called This is called throwing an exceptionthrowing an exception At some other place in your program you At some other place in your program you
place the code that deals with the place the code that deals with the exceptional caseexceptional case
This is called This is called handling the exceptionhandling the exception
Slide 16- 7
A Toy ExampleA Toy Example
Exception handling is meant to be used Exception handling is meant to be used sparingly in situations that are generally sparingly in situations that are generally not reasonable introductory examplesnot reasonable introductory examples
For this example:For this example: Suppose milk is so important that we Suppose milk is so important that we
almost never run outalmost never run out We still would like our program to handle We still would like our program to handle
the situation of running out of milkthe situation of running out of milk
Slide 16- 8
The Milk Example (cont.)The Milk Example (cont.)Code to handle the normal situations involvingCode to handle the normal situations involvingmilk, might be:milk, might be:
cout << "Enter number of donuts:\n"; cout << "Enter number of donuts:\n"; cin >> donuts; cin >> donuts; cout << "Enter number of glasses of milk:\n"; cout << "Enter number of glasses of milk:\n"; cin >> milk; cin >> milk; dpg = donuts /static_cast<double>(milk); dpg = donuts /static_cast<double>(milk); cout << donuts << " donuts.\n" cout << donuts << " donuts.\n" << milk << " glasses of milk.\n" << milk << " glasses of milk.\n" << "You have " << dpg << "You have " << dpg << " donuts per glass of milk.\n"; << " donuts per glass of milk.\n";
Slide 16- 9
If there is no milk, the code on the previous If there is no milk, the code on the previous slide results in a division by zeroslide results in a division by zero We could add a test case for this We could add a test case for this
situationsituation The next slide shows the program with The next slide shows the program with
the test casethe test case The two slides after that shows the The two slides after that shows the
program rewritten using a C++ exceptionprogram rewritten using a C++ exception
The No Milk ProblemThe No Milk Problem
Slide 16- 13
The try BlockThe try BlockThe program of Display 16.2 replaces the testThe program of Display 16.2 replaces the testcase in the if-else statement with case in the if-else statement with if(milk <= 0)if(milk <= 0) throw donuts; throw donuts;
This if-else code is found in the try blockThis if-else code is found in the try block try try {{ Some_Code Some_Code
}}
which encloses the code to handle the normal, which encloses the code to handle the normal, non error situationsnon error situations
Slide 16- 14
The Try Block OutlineThe Try Block OutlineThe try block encloses code that you want to The try block encloses code that you want to "try" but that could cause a problem"try" but that could cause a problem
The basic outline of a try block is:The basic outline of a try block is:
try try {{
Code_To_TryCode_To_Try Possibly_Throw_An_ExceptionPossibly_Throw_An_Exception
More_CodeMore_Code}}
Slide 16- 15
The ExceptionThe Exception
To throw an exception, a throw-statement To throw an exception, a throw-statement is used to throw a valueis used to throw a value In the milk example:In the milk example:
throw donuts; throw donuts;throws an throws an integerinteger value. value.
The value thrown is sometimes called an The value thrown is sometimes called an exceptionexception
You can throw a value of any typeYou can throw a value of any type
Slide 16- 16
The catch-blockThe catch-blockSomething that is thrown goes from one placeSomething that is thrown goes from one placeto anotherto another
A C++ throw causes the flow of control to go A C++ throw causes the flow of control to go to another placeto another place When an exception is thrown, the try block When an exception is thrown, the try block
stops executing and the catch-block begins stops executing and the catch-block begins executionexecution
This is This is catching catching oror handling the exception handling the exception
Slide 16- 17
The Milk catch-blockThe Milk catch-blockThe catch-block from the milk example looksThe catch-block from the milk example lookslike, but is not, a function definition with a like, but is not, a function definition with a parameter:parameter: catch(int e) //catch parameter is e catch(int e) //catch parameter is e
{{ cout << e << donuts, and no milk!\n" cout << e << donuts, and no milk!\n" << "Go buy some milk.\n"; << "Go buy some milk.\n"; } } If no exception is thrown, the catch-block is If no exception is thrown, the catch-block is
ignored during program executionignored during program execution
Slide 16- 18
The catch-block ParameterThe catch-block Parameter
The catch-block parameter, (recall that the The catch-block parameter, (recall that the catch-block is not a function) does two catch-block is not a function) does two things:things: The type of the catch-block parameter The type of the catch-block parameter
identifies the kind of value the catch-identifies the kind of value the catch-block can catchblock can catch
The catch-block parameter provides a The catch-block parameter provides a name for the value caught so you can name for the value caught so you can write code using the value that is caughtwrite code using the value that is caught
Slide 16- 19
try-blocks and if-elsetry-blocks and if-elsetry-blocks are very similar to if-else statementstry-blocks are very similar to if-else statements If everything is normal, the entire try-block is If everything is normal, the entire try-block is
executedexecuted else, if an exception is thrown, the catch-block else, if an exception is thrown, the catch-block
is executedis executed
A big difference between try-blocks and if-elseA big difference between try-blocks and if-elsestatements is the try-block's ability to send a statements is the try-block's ability to send a message to one of its branchesmessage to one of its branches
Slide 16- 20
try-throw-catch Reviewtry-throw-catch Review
This is the basic mechanism for throwing This is the basic mechanism for throwing and catching exceptionsand catching exceptions The try-block includes a throw-statementThe try-block includes a throw-statement If an exception is thrown, the try-block If an exception is thrown, the try-block
ends and the catch-block is executedends and the catch-block is executed If no exception is thrown, then after the If no exception is thrown, then after the
try-block is completed, execution try-block is completed, execution continues with the code following the continues with the code following the catch-block(s)catch-block(s)
Slide 16- 21
Defining an Exception ClassDefining an Exception Class
Because a throw-statement can throw a value of Because a throw-statement can throw a value of
any type, it is common to define a class whose any type, it is common to define a class whose objects can carry the kind of information youobjects can carry the kind of information youwant thrown to the catch-blockwant thrown to the catch-block
A more important reason for a specialized A more important reason for a specialized exception class is so you can have a different exception class is so you can have a different type to identify each possible kind of exceptionaltype to identify each possible kind of exceptionalsituationsituation
Slide 16- 22
An exception class is just a class that An exception class is just a class that happens to be used as an exception classhappens to be used as an exception class
See the next example of a program with a See the next example of a program with a programmer defined exception class programmer defined exception class
The Exception ClassThe Exception Class
Slide 16- 25
Throwing a Class TypeThrowing a Class TypeThe program in Display 16.3 uses the The program in Display 16.3 uses the throw-statementthrow-statement throw NoMilk(donuts); throw NoMilk(donuts); This invokes a constructor for the class NoMilkThis invokes a constructor for the class NoMilk The constructor takes a single argument of The constructor takes a single argument of
type inttype int The NoMilk object is what is thrownThe NoMilk object is what is thrown The catch-block then uses the statementThe catch-block then uses the statement
e.get_donuts( ) e.get_donuts( )to retrieve the number of donuts to retrieve the number of donuts
Slide 16- 26
A try-block can throw any number of exceptions A try-block can throw any number of exceptions of different typesof different types In any one execution, only one exception can In any one execution, only one exception can
be thrownbe thrown Each catch-block can catch only one Each catch-block can catch only one
exceptionexception Multiple catch-blocks may be usedMultiple catch-blocks may be used
A parameter is not required in a catch-blockA parameter is not required in a catch-block
A sample program with two catch-blocks is A sample program with two catch-blocks is found in next program.found in next program.
Multiple Throws and CatchesMultiple Throws and Catches
Slide 16- 30
A Default catch-blockA Default catch-blockWhen catching multiple exceptions, write the When catching multiple exceptions, write the catch-blocks for the most specific exceptions catch-blocks for the most specific exceptions firstfirst Catch-blocks are tried in order and the first one Catch-blocks are tried in order and the first one
matching the type of exception is executedmatching the type of exception is executed
A default (and last) catch-block to catch any A default (and last) catch-block to catch any exception can be made using "…" as the exception can be made using "…" as the catch-block parametercatch-block parameter catch(…) catch(…) { <the catch block code> } { <the catch block code> }
Slide 16- 31
Exception Class DivideByZeroException Class DivideByZeroIn the last program, exception class In the last program, exception class DivideByZero was defined as DivideByZero was defined as class DivideByZero class DivideByZero { } ; { } ; This class has no member variables or This class has no member variables or
member functionsmember functions This is a trivial exception class This is a trivial exception class DivideByZero is used simply to activate the DivideByZero is used simply to activate the
appropriate catch-blockappropriate catch-block There is nothing to do with the catch-block There is nothing to do with the catch-block
parameter so it can be omitted as shown in the parameter so it can be omitted as shown in the last program.last program.
Slide 16- 32
Exceptions In FunctionsExceptions In FunctionsIn some cases, an exception generated in a In some cases, an exception generated in a function is not handled in the functionfunction is not handled in the function It might be that some programs should end, It might be that some programs should end,
while others might do something else, so while others might do something else, so within the function you might not know how to within the function you might not know how to handle the exceptionhandle the exception
In this case, the program places the function In this case, the program places the function invocation in a try block and catches the invocation in a try block and catches the exception in a following catch-blockexception in a following catch-block
Slide 16- 33
Function safe_divideFunction safe_divideThe next program includes a function that The next program includes a function that throws, but does not catch an exceptionthrows, but does not catch an exception In function safe_divide, the denominator is In function safe_divide, the denominator is
checked to be sure it is not zero. If it is checked to be sure it is not zero. If it is zero, an exception is thrown:zero, an exception is thrown: if (bottom == 0) if (bottom == 0) throw DivideByZero( ); throw DivideByZero( );
The call to function safe_divide is found in The call to function safe_divide is found in the try-block of the programthe try-block of the program
If a function does not catch an exception it should If a function does not catch an exception it should warn programmers than an exception might be warn programmers than an exception might be thrown by the functionthrown by the function An exception specification, also called a throw An exception specification, also called a throw
list, appears in the function declaration and list, appears in the function declaration and definition:definition:
double safe_divide(int n, int d) throw double safe_divide(int n, int d) throw (DivideByZero);(DivideByZero); if multiple exceptions are thrown and not caught if multiple exceptions are thrown and not caught
by a function:by a function: double safe_divide(int n, int d) double safe_divide(int n, int d) throw (DivideByZero, OtherException); throw (DivideByZero, OtherException);
Slide 16- 34
Exception SpecificationException Specification
Slide 16- 37
Exceptions Not ListedExceptions Not Listed
If an exception is not listed in an exception If an exception is not listed in an exception specification and not caught by the function:specification and not caught by the function: The program ends The program ends
If there is no exception specification at all, it is If there is no exception specification at all, it is the same as if all possible exceptions are listedthe same as if all possible exceptions are listed These exceptions will be treated "normally" These exceptions will be treated "normally"
An empty exception specification list means An empty exception specification list means that no exceptions should be thrown and not that no exceptions should be thrown and not caughtcaught
Slide 16- 38
Sample Sample Exception SpecificationsException Specifications
void some_function ( ) throw ( );void some_function ( ) throw ( );//empty exception list; so all exceptions not //empty exception list; so all exceptions not // caught by the function end the program// caught by the function end the program
void some_function( ) throw(DivideByZero, void some_function( ) throw(DivideByZero, OtherException);OtherException);//Exceptions DivideByZero and //Exceptions DivideByZero and //OtherException//OtherException//treated normally. All others end the //program //treated normally. All others end the //program
Sample Sample Exception SpecificationsException Specifications
void some_function( );void some_function( );// All exceptions of all types treated // All exceptions of all types treated //normally//normally// If not caught by a catch-block, the // If not caught by a catch-block, the //program ends//program ends
Slide 16- 40
Type ConversionType Conversion
No automatic type conversions are done No automatic type conversions are done with exceptionswith exceptions if double is in the exception specification, if double is in the exception specification,
an int cannot be thrown unless int is an int cannot be thrown unless int is also in the exception specificationalso in the exception specification
No automatic conversion is performedNo automatic conversion is performed
Slide 16- 41
Section 16.1 ConclusionSection 16.1 ConclusionCan youCan you
List the three components of exception List the three components of exception handling?handling?
Write code to catch an exception of type Write code to catch an exception of type char?char?
Create an exception specification for a Create an exception specification for a function?function?
Create an exception class?Create an exception class?
Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
16.216.2Programming Techniques Programming Techniques
for Exception-Handlingfor Exception-Handling
Slide 16- 43
Programming TechniquesProgramming Techniquesfor Exception Handlingfor Exception Handling
A guideline for exception handling is to A guideline for exception handling is to separate throwing an exception and catching separate throwing an exception and catching an exception into separate functions an exception into separate functions Place the throw-statement in one function Place the throw-statement in one function
and list the exception in the exception and list the exception in the exception specificationspecification
Place the function invocation and catch-Place the function invocation and catch-clause in a try-block of a different functionclause in a try-block of a different function
Slide 16- 44
try and throw…Againtry and throw…Again
Here is a general approach to useHere is a general approach to usein using throw:in using throw:
void functionA( ) throw void functionA( ) throw (MyException)(MyException)
{{ … … throw MyException(<an argument?>); throw MyException(<an argument?>); } }
next ==>
Slide 16- 45
catch…againcatch…againUsing FunctionA from the previous slide, hereUsing FunctionA from the previous slide, hereis how to catch MyException:is how to catch MyException: void functionB( )void functionB( ){ …{ …trytry { … { … functionA( ); functionA( ); … …
}} catch(MyException e) catch(MyException e) { < handle the exception> { < handle the exception> } }}}
Slide 16- 46
When to Throw An ExceptionWhen to Throw An ExceptionThrowing exceptions is generally reserved forThrowing exceptions is generally reserved forthose cases when handling the exceptional those cases when handling the exceptional case depends on how and where the function case depends on how and where the function was invokedwas invoked In these cases it is usually best to let the In these cases it is usually best to let the
programmer calling the function handle the programmer calling the function handle the exceptionexception
An uncaught exception ends your programAn uncaught exception ends your program
If you can easily write code to handle the If you can easily write code to handle the problem do not throw an exceptionproblem do not throw an exception
Slide 16- 47
Nested try-catch BlocksNested try-catch BlocksAlthough a try-block followed by its catch-blockAlthough a try-block followed by its catch-blockcan be nested inside another try-blockcan be nested inside another try-block It is almost always better to place the nested It is almost always better to place the nested
try-block and its catch-block inside a function try-block and its catch-block inside a function definition, then invoke the function in the outerdefinition, then invoke the function in the outertry-blocktry-block
An error thrown but not caught in the innerAn error thrown but not caught in the innertry-catch-blocks is thrown to the outer try-blocktry-catch-blocks is thrown to the outer try-blockwhere it might be caughtwhere it might be caught
Slide 16- 48
Overuse of ExceptionsOveruse of Exceptions
Throwing an exception allows you to transfer Throwing an exception allows you to transfer flow of control to almost any place in your flow of control to almost any place in your programprogram
Such un-restricted flow of control is generallySuch un-restricted flow of control is generallyconsidered poor programming style as it makesconsidered poor programming style as it makesprograms difficult to understandprograms difficult to understand
Exceptions should be used sparingly and only Exceptions should be used sparingly and only when you cannot come up with an alternative when you cannot come up with an alternative that produces reasonable codethat produces reasonable code
Slide 16- 49
Exception Class HierarchiesException Class HierarchiesIt can be useful to define a hierarchy of It can be useful to define a hierarchy of exception classes.exception classes. You might have an ArithmeticError You might have an ArithmeticError
exception class with DivideByZeroError as exception class with DivideByZeroError as a derived classa derived class
Since a DivideByZeroError object is also an Since a DivideByZeroError object is also an
ArithmeticError object, every catch-block ArithmeticError object, every catch-block for an ArithmeticError will also catch a for an ArithmeticError will also catch a DivideByZeroErrorDivideByZeroError
Slide 16- 50
Checking For Available MemoryChecking For Available MemoryThe new operator allocates memory from the The new operator allocates memory from the freestore: NodePtr pointer = new Node;freestore: NodePtr pointer = new Node; What if there is no memory available?What if there is no memory available? bad_alloc is a predefined exception and can be bad_alloc is a predefined exception and can be
used in this way since new throws a bad_alloc used in this way since new throws a bad_alloc exception:exception:
try try { NodePtr pointer = new Node; { NodePtr pointer = new Node; } } catch(bad_alloc) catch(bad_alloc) { cout << "Ran out of memory!"; { cout << "Ran out of memory!"; } }
Slide 16- 51
Rethrowing an ExceptionRethrowing an Exception
The code within a catch-block can throw The code within a catch-block can throw an exceptionan exception This feature can be used to pass the This feature can be used to pass the
same or a different exception up the same or a different exception up the chain of exception handling blockschain of exception handling blocks
Slide 16- 52
Section 16.2 ConclusionSection 16.2 Conclusion
Can youCan you
Describe what happens if an exception is Describe what happens if an exception is never caught?never caught?
Write code that nests a try-block inside Write code that nests a try-block inside another try-block?another try-block?
Describe the type of situations in which Describe the type of situations in which exceptions should not be thrown?exceptions should not be thrown?