Exception Handling• Use exception handling to write programs
that are– Clearer– More robust– More fault-tolerant
• Exception examples– Failure of new to obtain enough memory– An out-of-bounds array subscript– Arithmetic overflow– Division by zero– Invalid function parameters
Error-handling Code
• Typically error-handling code is put where errors are expected to occur– Advantage
• Programmers can easily check to if error handling has been done in the immediate vicinity of the code
– Disadvantage• Code may become cluttered with too much error
processing
C++’s Exception Handling• Using C++’s exception handling removes
most of the error handling code from the main program – Improves program readability and
modifiability– Can handle “synchronous errors”
• Such as division by zero
– Cannot handle “asynchronous situations”• Such as network message arrivals• Mouse clicks
C++’s Exception Handling
• Exception handling is used to– Allow the system to recover from an
exception– Or (in the case of an unrecoverable error)
clean up the mess & shut down gracefully
The Basics: try, throw, & catch• Code that may generate an exception is encased
in a try block– Within the try bock an exception is thrown
• After the try block, a catch block will catch and handle the exception, so that the program can return to its normal state
– Program will search for a catch block with the same parameter type as the exception type
• If an exception is not handled, the program will terminate
Exception Class & Functionclass DBZException { public: DBZException()
:message("ERROR: division by zero"){}
void print() const {cout<<message<<endl;} private: const char *message;};
double quotient( int num, int den ){if ( den == 0 )
throw DBZException();return static_cast<double>(num)/den;
}(See DBZException.cpp.txt)
Mainint main(){ int num1, num2; double result; cout << "Enter two integers (EOF to end): "; while ( cin >> num1 >> num2 ) { try { result = quotient( num1, num2 ); cout<<"The quotient is: "<<result<<endl; } catch ( DBZException ex ) { ex.print(); } cout<<"\nEnter two integers (EOF to end): "; }
return 0; }
Output• Even thought the user made a mistake, the
program can continue without an abend (ABnormal END)
Enter two integers (EOF to end): 3 4The quotient is: 0.75
Enter two integers (EOF to end): 4 0ERROR: division by zero
Enter two integers (EOF to end): 4 5The quotient is: 0.8
End-of-File Marker
• File ends with a end-of-file (EOF) marker
– EOF key combinations on different systems:
• UNIX systems: <ctrl>d
• IBM PC and compatibles: <ctrl>z
• Macintosh: <ctrl>d
Throwing an Exception• A throw indicates that an exception occurred
– The throw operand can be of any type
– Can throw objects not intended for error handling
• When an operand is thrown – A temporary copy is made & initialized
• When this operand is caught– It initializes exception handler’s parameter
• When the exception handler completes execution and exits, the temporary object is destroyed
Throwing an Exception II
• If a handler is not found within a try block – The program will search for a matching handler
in the next nested try block, until it is found
• All exceptions thrown outside a try block will terminate the program
• All objects declared in a try block will be destroyed before an exception is thrown from that block
New Exception Classclass DBZException {
public:
DBZException():message("ERROR: division by zero"){}
void print() const {cout<<message<<endl; }
private: const char *message;};
class NIFException {
public:
NIFException()
:message("ERROR: numerator is five"){}
void print() const {
cout<<message<<endl; }
private:
const char *message;
};
Functionsvoid checkNumeratorIs5(int n){
if(n==5) throw NIFException();
if(n==100) throw int();
}
double quotient( int num, int den ){
if ( den == 0 )
throw DBZException();
try{
checkNumeratorIs5(num);
cout<<"No exception in QUOTIENT()"<<endl;}
catch(int e){
cout<<"Type INT exception thrown"<<endl;}
return static_cast< double > ( num ) / den;
}
Mainint main(){
int num1, num2;
double result;
cout << "Enter two integers (EOF to end): ";
while ( cin >> num1 >> num2 ) {
try{
result = quotient( num1, num2 );
cout<<"The quotient is:"<<result<<endl;}
catch ( DBZException e ) {
e.print(); }
catch ( NIFException e ) {
e.print(); }
cout<<"\nEnter two integers (EOF to end): "; }
return 0;}
OutputEnter two integers (EOF to end): 1 2
No exception in QUOTIENT()
The quotient is: 0.5
Enter two integers (EOF to end): 5 2
ERROR: numerator is five
Enter two integers (EOF to end): 100 4
Type INT exception thrown
The quotient is: 25(See throwing.cpp.txt)
Catching an Exception
• The catch block is used to 1. Catch an exception
2. Execute the code within the block
• The parameter in a catch statement can be named or unnamed– The handler catch(…) will catch any exception
• If no matching parameter type is found for a thrown object, the program terminates
Catching an Exception II
• A catch block can throw another kind of exception or re-throw itself– These exceptions will not be caught by any catch
blocks listed after the current catch block – They will be caught after the next outer try
block – If not caught, they will terminate the program
Exception Classclass DBZException { public: DBZException()
:message("ERROR: division by zero"){}
void print() const {cout<<message<<endl;} private: const char *message;};
(See catching.cpp.txt)
Functionsvoid check(int n){
if(n==100) throw int();
}
double quotient( int num, int den ){
if ( den == 0 )
throw DBZException();
try{
check(num); }
catch( int ){ //unnamed parameter
cout<<"Type INT exception thrown"<<endl;
throw; //re-throw exception
}
return static_cast< double > ( num ) / den;
}
void main(){
int num1, num2;
double result;
cout << "Enter two integers (EOF to end): ";
try{
while ( cin >> num1 >> num2 ) {
try {
result = quotient( num1, num2 );
cout<<"The quotient is:"<<result<<endl;}
catch ( DBZException e ) {
e.print();
throw float(); }
catch (...) {
cout<<"UNDEFINED ERROR I"<<endl; }
cout<<"\nEnter two integers : ";}
}
catch(...){
cout<<"UNDEFINED ERROR II"<<endl;} }
OutputEnter two integers (EOF to end): 100 25
Type INT exception thrown
UNDEFINED ERROR I
Enter two integers (EOF to end): 100 0
ERROR: division by zero
UNDEFINED ERROR II
(program terminates)
Top Related