Chapter 17: Advanced C++ Topics III

Lecture Goals

Exception Handling

Signaling Error Conditions

Syntax 17.8: Throwing an Exception

throw expression;
Example:
throw logic_error("illegal future_value parameter");
Purpose: Abandon this function and throw a value to an exception handler.

Catching Exceptions

Syntax 17.9: Try Block

try
{

statements
}
catch (type_name1 variable_name1)
{
statements
}
catch (type_name2 variable_name2)
{
statements
}
...
catch (type_namen variable_namen)
{
statements
}
Example:
try
{
double fvalue = future_value(init, interest, years);
cout << "The future value is " << fvalue << endl;
}
catch(logic_error& e)
{
cout << "Processing error " << e.what() << "\n";
}
Purpose: Provide one or more handlers for types of exceptions that may be thrown when executing a block of statements.

Exception Handling (exception1.cpp)

Exception Handling (exception2.cpp)

Stack Unwinding

Exception Handling (product1.cpp)

Exception Handling (product2.cpp)

Exception Specifications

Syntax 17.10: Exception Specification

return_type function_name(parameters)
throw (type_name1, type_name2, ..., type_namen)
Example:
void process_products(fstream& fs)
throw(UnexpectedEndOfFile, bad_alloc)
Purpose: List the types of all exceptions that a function can throw.