1. Except
1. Except
States?
Ignore them:
Wrong thing to do for all but demo programs.
critical missions.
try {…}:
defines, for thrown exceptions, an enclosing context
with specified catch handlers
catch(E e) {…}:
exception handler catch(E e) responds to an exception
object of type “E”
Example
If no exception is thrown, the code in the try block is executed,
the
catch clause is skipped, and computation resumes after the
try If the exception is
catch
{ clause. thrown in some
lower level scope,
// some code that may throw an exception defined, perhaps,
} by a called function
Catch(exception &e) within the try
block, all local
{
objects in that
// some processing to attempt to recover from error scope are
// based on information carried by the exception destroyed as the
} exception moves
out of that scope.
If an exception is thrown somewhere in the try block, the
remaining code in the try block is skipped, and a matching
catch clause is entered, if found. Computation resumes after
the last statement in matching catch clause. Matching is based
on the type of the exception.
Chained Handlers
Exception handlers are often chained at the
end of a try block, e.g.:
try {
// some code that may throw an exception
}
Catch(T1 t1) {
// processing for type T1
}
Catch(T2 t2) {
// processing for type T2
}
Example:
void Arnold() { std::cout << “I’ll be back” }
int main() {
set_terminate(Arnold);
:
}
Rethrowing Exceptions
If your catch handler does not completely handle an
exception you may re-throw it to the next enclosing
context.
catch(E e)
{
// processing to handle e is incomplete
throw;
}
logic_error
runtime_error
domain_error
range_error
invalid_argument
overflow_error
length_error
underflow_error
out_of_range
Exception Specifications
All exception specifications have been removed from C+
+11 except for throw() and nothrow().
void f() throw (E1, E2, E3);
declares that f may throw any of E1, E2, or E3.
void f() throw()
declares that no exceptions are thrown in f.
void f()
declares that any type exception may be thrown in f.
Specification Violations
If an exception specification is violated, the special
function unexpected() is called when the exception is
thrown.
void FreddyKrueger() { … }
int main()
{
set_unexpected(FreddyKrueger);
:
}
Exception Safety (Sutter,
2000)
Basic guarantee:
In the presence of exceptions thrown by called
global functions, object messages, template
parameters, or library calls, the code:
will not leak resources.
will maintain in a consistent, if unpredictable,
state.
Exception Safety
Strong guarantee:
If an operation terminates because of an exception,
program state will remain unchanged.