Handling Exceptions
An exception interrupts the normal flow of control in a program. An exception throws an object from the point where the exception is raised to the point where the exception is handled. In between those points, function calls are aborted, and local scopes are abruptly exited. Local and temporary objects in those scopes are destroyed.
This section discusses exception handling in general and the
try statement in particular. For information about other
aspects of exception handling, see Chapter
3, which describes the throw
expression, and Chapter
5, which describes function try blocks and throw specifications. See also <exception> and <stdexcept> in Chapter 13 for information about the
standard exception classes and related functions.
Tip
As the name implies, an exception is used for exceptional
circumstances, such as indexing a vector with an index that is out of
bounds. The intention in C++ is that try statements should have near zero cost,
but throwing and handling an exception can be expensive in terms of
performance.
A try statement establishes a
local scope plus exception handlers. A try statement begins with the try keyword followed by a compound statement
and one or more catch handlers. Each
catch handler has an exception type
in parentheses followed by a compound statement. The exception type can
be a sequence of type specifiers followed by an optional declarator, or
it can be an ellipsis:
trycompound-statementcatch(typedeclarator)compound-statementcatch( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access