Dale Roberts Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI E-mail:...
-
Upload
justyn-gayden -
Category
Documents
-
view
219 -
download
2
Transcript of Dale Roberts Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI E-mail:...
Dale Roberts
Exception HandlingException Handling
Dale Roberts, LecturerComputer Science, IUPUIE-mail: [email protected]
Department of Computer and Information Science,School of Science, IUPUI
Fall 2003
Dale Roberts
Purpose of Exception HandlingPurpose of Exception Handling
Deal with errors in an elegant manner Deal with errors in an elegant manner
Write clearer, most robust, and fault tolerant Write clearer, most robust, and fault tolerant program program
Error handling code Error handling code Minimum --- Casual Systems Minimum --- Casual Systems
Extensive --- Commercial products Extensive --- Commercial products
Dale Roberts
Dealing with ErrorsDealing with ErrorsErrors are interspersed throughout the software. Errors Errors are interspersed throughout the software. Errors are handled where they occur. are handled where they occur.
Programmer can see the error processing near to the code and Programmer can see the error processing near to the code and determine the appropriateness of the error processing code. determine the appropriateness of the error processing code. Code becomes "polluted" with error processing. More difficult for a Code becomes "polluted" with error processing. More difficult for a programmer concerned with the application itself to read the code programmer concerned with the application itself to read the code and determine if the code is functioning completely. and determine if the code is functioning completely.
User exception handling techniques User exception handling techniques Remove error code from the "main code" Remove error code from the "main code" better readability and modifiabilitybetter readability and modifiability
Exception Handling – remove the error handling code Exception Handling – remove the error handling code from the “main-line” of the program’s execution – from the “main-line” of the program’s execution – improves program readability and maintainability – improves program readability and maintainability – catchcatch all kinds of exceptions, or a subset of them – all kinds of exceptions, or a subset of them – programs become more robustprograms become more robustMemory allocation, Arithmetic Exceptions, Invalid Memory allocation, Arithmetic Exceptions, Invalid Parameters, Array Bounds, etc. – Parameters, Array Bounds, etc. – synchronous errors.synchronous errors.
Dale Roberts
Dealing with ErrorsDealing with Errors
Used in situations where the system can Used in situations where the system can recover from the error causing the exception – recover from the error causing the exception – the recovery procedures is called the the recovery procedures is called the exception exception handlerhandler..
Exception handling is typically used when the Exception handling is typically used when the error will be dealt with by a different part of the error will be dealt with by a different part of the program (i.e. a different scope) from where the program (i.e. a different scope) from where the error was detected.error was detected.
Particularly useful for gParticularly useful for graceful degradation.raceful degradation.
Use only to process exceptional situations.Use only to process exceptional situations.
Dale Roberts
Dealing with ErrorsDealing with Errors
To process exceptions for program components To process exceptions for program components that are not geared to handle those exceptions that are not geared to handle those exceptions directly.directly.To process exception from software To process exception from software components, such as functions, libraries, components, such as functions, libraries, classes, etc., that are likely to be widely used classes, etc., that are likely to be widely used and where it does not make sense for those and where it does not make sense for those components to handle their own exceptions.components to handle their own exceptions.To handle error processing in a uniform manner To handle error processing in a uniform manner across large-scale projects.across large-scale projects.Use assert macro - if an assertion is false, Use assert macro - if an assertion is false, program terminates - useful at debugging program terminates - useful at debugging
Dale Roberts
Dealing with ErrorsDealing with Errors
Ignore exceptions! Ignore exceptions!
Abort program - what if resources were Abort program - what if resources were allocated to a program and it aborted? allocated to a program and it aborted? ("Resource Leak") ("Resource Leak")
Set and test error indicators - need to check Set and test error indicators - need to check them at all points in the program them at all points in the program
Dale Roberts
Error Handling -- Method to Cope with UncertaintiesError Handling -- Method to Cope with Uncertainties
A Function which Finds that it Cannot Cope With a A Function which Finds that it Cannot Cope With a Problem Throws an Exception, Hoping that Caller can Problem Throws an Exception, Hoping that Caller can Handle that Problem Handle that Problem
A Function that Wants to Handle that Kind of a Problem A Function that Wants to Handle that Kind of a Problem can Indicate that it is Willing to Catch that Exception can Indicate that it is Willing to Catch that Exception
Method of Transferring Control and Information to an Method of Transferring Control and Information to an Associated Exception Handler Associated Exception Handler
A A trytry Block Constitutes the Section of the Program Block Constitutes the Section of the Program that is Subject to Exception Checking that is Subject to Exception Checking
A Handler is Invoked with a A Handler is Invoked with a throwthrow Expression from Expression from
within the within the trytry Block Block
The Handler is the The Handler is the catchcatch Function Function
Dale Roberts
Error Handling -- Method to Cope with Uncertainties (cont)Error Handling -- Method to Cope with Uncertainties (cont)
Dale Roberts
Invoking of HandlerInvoking of Handler
The Type of the Object Argument of the The Type of the Object Argument of the throwthrow Expression Determines the Appropriate Expression Determines the Appropriate catchcatch Invocation Invocation
A A throwthrow Expression Without an Argument Re- Expression Without an Argument Re-throws the Exception Being Handled Again. throws the Exception Being Handled Again. Such a Such a throwthrow Expression MAY APPEAR ONLY Expression MAY APPEAR ONLY IN A HANDLER or in a Function Directly Called IN A HANDLER or in a Function Directly Called From the Handler From the Handler
The The catch (...)catch (...) Handler, if Present, CAN Handle Handler, if Present, CAN Handle ALL Exception Classes ALL Exception Classes
Dale Roberts
Invoking of HandlerInvoking of Handler
If NO Appropriate Handler is Present, the If NO Appropriate Handler is Present, the unexpected()unexpected() Function is Invoked. It Passes the Function is Invoked. It Passes the Control to Control to terminate()terminate() Function and can Cause Function and can Cause Termination Termination
The The throwthrow Expression is First Passed to the Expression is First Passed to the Appropriate Constructor for the Class -- A Appropriate Constructor for the Class -- A Default Constructor MAY be Created, if Needed Default Constructor MAY be Created, if Needed -- No Constructor is Used for Non-Classes. The -- No Constructor is Used for Non-Classes. The Processing is then Passed to the Handler Processing is then Passed to the Handler
Dale Roberts
catch Handlerscatch Handlers
The The catchcatch Handler MUST IMMEDIATELY Handler MUST IMMEDIATELY FOLLOW the Appropriate FOLLOW the Appropriate trytry Block or Other Block or Other catchcatch Handlers Handlers
The Placement Order is Significant. Control is The Placement Order is Significant. Control is Passed to the FIRST HANDLER THAT CAN Passed to the FIRST HANDLER THAT CAN HANDLE THE CONDITION HANDLE THE CONDITION
The The catch(...)catch(...) Handler, if Present, SHOULD BE Handler, if Present, SHOULD BE THE LAST HANDLER THE LAST HANDLER
Dale Roberts
Simple Exception Handler -- Example Simple Exception Handler -- Example #include <iostream>#include <iostream> main(){main(){ //try Block//try Block trytry {throw(long 1); //catch(long) call} {throw(long 1); //catch(long) call} //Handlers//Handlers catch (int x)catch (int x) {cout << "Catch Integer " << x << endl;}{cout << "Catch Integer " << x << endl;} catch (long x)catch (long x) {cout << "Catch Long " << x << endl;}{cout << "Catch Long " << x << endl;} catch (...)catch (...) {cout << "Catch Rest" << endl;}{cout << "Catch Rest" << endl;} }} OUTPUT WILL BE:OUTPUT WILL BE: ------ ---- -------- ---- -- Catch Long 1Catch Long 1
Earlier g++ compiler verions required the usae of the =fhandle-exceptions or –Earlier g++ compiler verions required the usae of the =fhandle-exceptions or –fexceptions flags. The current g++ compiler support exception handling by default.fexceptions flags. The current g++ compiler support exception handling by default.
Dale Roberts
An Exception Handler Class -- ExampleAn Exception Handler Class -- Example#include<stream.h>#include<stream.h>#include<stdlib.h> //exit()#include<stdlib.h> //exit()class zero{class zero{ public:public: zero() //Constructorzero() //Constructor {cout<<"Class Zero Constructor Invoked!!"<<endl;}{cout<<"Class Zero Constructor Invoked!!"<<endl;}};};//Exception Checker Function//Exception Checker Functionvoid zero_check(int i){void zero_check(int i){ if (i == 0)if (i == 0) throw zero(); //Argument is of zero class type.}throw zero(); //Argument is of zero class type.}main(){main(){ //try block//try block try{for (int i = 2; ; i--){try{for (int i = 2; ; i--){ zero_check(i);zero_check(i); cout << "Reciprocal: " << 1.0/i << endl;}}cout << "Reciprocal: " << 1.0/i << endl;}} //Handler//Handler catch(zero)catch(zero) {cout << "DIVIDE BY ZERO -- ERROR!!\n"; exit(-1);}{cout << "DIVIDE BY ZERO -- ERROR!!\n"; exit(-1);}}} OUTPUT WILL BE:OUTPUT WILL BE: ------ ---- --------- ---- --- Reciprocal: 0.5Reciprocal: 0.5 Reciprocal: 1Reciprocal: 1 Class Zero Constructor Invoked!!Class Zero Constructor Invoked!! DIVIDE BY ZERO -- ERROR!! DIVIDE BY ZERO -- ERROR!!
Dale Roberts
1. Class 1. Class definitiondefinition
1.1 Function 1.1 Function definitiondefinition
1 // Fig. 23.1: fig23_01.cpp
2 // A simple exception handling example.
3 // Checking for a divide-by-zero exception.
4 #include <iostream>
5
6 using std::cout;
7 using std::cin;
8 using std::endl;
9
10 // Class DivideByZeroException to be used in exception
11 // handling for throwing an exception on a division by zero.
12 class DivideByZeroException {
13 public:
14 DivideByZeroException()
15 : message( "attempted to divide by zero" ) { }
16 const char *what() const { return message; }
17 private:
18 const char *message;
19 };
20
21 // Definition of function quotient. Demonstrates throwing
22 // an exception when a divide-by-zero exception is encountered.
23 double quotient( int numerator, int denominator )
24 {
25 if ( denominator == 0 )
26 throw DivideByZeroException();
27
28 return static_cast< double > ( numerator ) / denominator;
29 }
Dale Roberts
1.2 Initialize 1.2 Initialize variablesvariables
2. Input data2. Input data
2.1 2.1 trytry and and catchcatch blocksblocks
2.2 Function 2.2 Function callcall
3. Output 3. Output resultresult
30
31 // Driver program
32 int main()
33 {
34 int number1, number2;
35 double result;
36
37 cout << "Enter two integers (end-of-file to end): ";
38
39 while ( cin >> number1 >> number2 ) {
40
41 // the try block wraps the code that may throw an
42 // exception and the code that should not execute
43 // if an exception occurs
44 try {
45 result = quotient( number1, number2 );
46 cout << "The quotient is: " << result << endl;
47 }
48 catch ( DivideByZeroException ex ) { // exception handler
49 cout << "Exception occurred: " << ex.what() << '\n';
50 }
51
52 cout << "\nEnter two integers (end-of-file to end): ";
53 }
54
55 cout << endl;
56 return 0; // terminate normally
57 }
Dale Roberts
Program Program OutputOutput
Enter two integers (end-of-file to end): 100 7The quotient is: 14.2857 Enter two integers (end-of-file to end): 100 0Exception occurred: attempted to divide by zero Enter two integers (end-of-file to end): 33 9The quotient is: 3.66667 Enter two integers (end-of-file to end):
Dale Roberts
Throwing an ExceptionThrowing an Exceptionthrow - throw - indicates an exception has occurredindicates an exception has occurred
Usually has one operand (sometimes zero) of any typeUsually has one operand (sometimes zero) of any typeIf operand an object, called an exception objectIf operand an object, called an exception objectConditional expression can be thrownConditional expression can be thrown
Code referenced in a Code referenced in a trytry block can throw an exception block can throw an exceptionException caught by closest exception handler Exception caught by closest exception handler Control exits current try block and goes to Control exits current try block and goes to catchcatch handler (if it handler (if it exists)exists)Example (inside function definition)Example (inside function definition)
if ( denominator == 0 )if ( denominator == 0 )
throw DivideByZeroException();throw DivideByZeroException();Throws a Throws a dividebyzeroexceptiondividebyzeroexception object object
Exception not required to terminate programException not required to terminate programHowever, terminates block where exception occurredHowever, terminates block where exception occurred
Dale Roberts
Catching an ExceptionCatching an Exception
Exception handlers are in Exception handlers are in catchcatch blocks blocksFormat: Format: catch( catch( exceptionTypeexceptionType parameterNameparameterName){){
exception handling codeexception handling code
}}
Caught if argument type matches Caught if argument type matches throwthrow typetype
If not caught then If not caught then terminateterminate called which (by default) calls called which (by default) calls abortabort
Example:Example:catch ( DivideByZeroException ex) {catch ( DivideByZeroException ex) {
cout << "Exception occurred: " << ex.what() <<'\n'cout << "Exception occurred: " << ex.what() <<'\n'
}}
Catches exceptions of type Catches exceptions of type DivideByZeroExceptionDivideByZeroException
Dale Roberts
Catching an Exception (cont)Catching an Exception (cont)
Catch all exceptions Catch all exceptions catch(...)catch(...) - catches all exceptions - catches all exceptions
You do not know what type of exception occurredYou do not know what type of exception occurredThere is no parameter name - cannot reference the There is no parameter name - cannot reference the objectobject
If no handler matches thrown objectIf no handler matches thrown objectSearches next enclosing Searches next enclosing trytry block block
If none found, If none found, terminateterminate called called
If found, control resumes after last If found, control resumes after last catchcatch block blockIf several handlers match thrown object, first one If several handlers match thrown object, first one found is executedfound is executed
Dale Roberts
Catching an Exception (cont)Catching an Exception (cont)
catchcatch parameter matches thrown object when parameter matches thrown object whenThey are of the same typeThey are of the same type
Exact match required - no promotions/conversions Exact match required - no promotions/conversions allowedallowed
The The catchcatch parameter is a parameter is a publicpublic base class of base class of the thrown objectthe thrown objectThe The catchcatch parameter is a base-class pointer/ parameter is a base-class pointer/ reference type and the thrown object is a derived-reference type and the thrown object is a derived-class pointer/ reference typeclass pointer/ reference typeThe The catchcatch handler is handler is catch(catch( ...... ))Thrown Thrown constconst objects have objects have constconst in the in the parameter typeparameter type
Dale Roberts
Catching an Exception (cont)Catching an Exception (cont)
Unreleased resourcesUnreleased resources
Resources may have been allocated when Resources may have been allocated when exception thrownexception thrown
catchcatch handler should handler should deletedelete space allocated by space allocated by newnew and close any opened files and close any opened files
catchcatch handlers can throw exceptions handlers can throw exceptions
Exceptions can only be processed by outer Exceptions can only be processed by outer trytry blocksblocks
Dale Roberts
Rethrowing an ExceptionRethrowing an Exception
Rethrowing exceptionsRethrowing exceptions
Used when an exception handler cannot process an Used when an exception handler cannot process an exceptionexception
Rethrow exception with the statement:Rethrow exception with the statement:
throw;throw; No argumentsNo arguments
If no exception thrown in first place, calls If no exception thrown in first place, calls terminateterminate
Handler can always rethrow exception, even if it Handler can always rethrow exception, even if it performed some processingperformed some processing
Rethrown exception detected by next enclosing Rethrown exception detected by next enclosing trytry block block
Dale Roberts
1. Load 1. Load headerheader
1.1 Function 1.1 Function prototypeprototype
1 // Fig. 23.2: fig23_02.cpp
2 // Demonstration of rethrowing an exception.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <exception>
9
10 using std::exception;
11
12 void throwException()
13 {
14 // Throw an exception and immediately catch it.
15 try {
16 cout << "Function throwException\n";
17 throw exception(); // generate exception
18 }
19 catch( exception e )
20 {
21 cout << "Exception handled in function throwException\n";
Dale Roberts
2. Function 2. Function callcall
3. Output3. Output
Program Program OutputOutput
22 throw; // rethrow exception for further processing
23 }
24
25 cout << "This also should not print\n";
26 }
27
28 int main()
29 {
30 try {
31 throwException();
32 cout << "This should not print\n";
33 }
34 catch ( exception e )
35 {
36 cout << "Exception handled in main\n";
37 }
38
39 cout << "Program control continues after catch in main"
40 << endl;
41 return 0;
42 }
Function throwExceptionException handled in function throwExceptionException handled in mainProgram control continues after catch in main
Dale Roberts
Exception specificationsException specifications
Exception specification (Exception specification (throwthrow list) list) Lists exceptions that can be thrown by a functionLists exceptions that can be thrown by a function
Example:Example:
int g( double h ) throw ( a, b, c )int g( double h ) throw ( a, b, c ){{ // function body // function body}}
Function can throw listed exceptions or derived typesFunction can throw listed exceptions or derived types
If other type thrown, function If other type thrown, function unexpectedunexpected called called
throw() throw() (i.e., no (i.e., no throwthrow list) states that function will not throw any list) states that function will not throw any exceptionsexceptions
In reality, function can still throw exceptions, but calls In reality, function can still throw exceptions, but calls unexpected unexpected (more later)(more later)
If no If no throwthrow list specified, function can list specified, function can throwthrow any exception any exception
Dale Roberts
Processing Unexpected ExceptionsProcessing Unexpected Exceptions
Function Function unexpectedunexpectedCalls the function specified with Calls the function specified with set_unexpectedset_unexpected
Default:Default: terminateterminate
FunctionFunction terminate terminateCalls function specified withCalls function specified with set_terminateset_terminate
Default:Default: abort abort
set_terminateset_terminate and and set_unexpectedset_unexpectedPrototypes in Prototypes in <exception><exception> Take pointers to functions (i.E., Function name)Take pointers to functions (i.E., Function name)
Function must return Function must return voidvoid and take no arguments and take no argumentsReturns pointer to last function called by Returns pointer to last function called by terminateterminate or or unexpectedunexpected
Dale Roberts
UsagesUsages
Arithmetic Exceptions -- Divide by Zero Arithmetic Exceptions -- Divide by Zero
Range Exceptions -- Overflow, Underflow Range Exceptions -- Overflow, Underflow
Memory Exceptions -- Dynamic Memory Memory Exceptions -- Dynamic Memory Allocations Allocations