Namespaces
Variants
Views
Actions

throw expression

From cppreference.com
 
 
C++ language
General topics
Preprocessor
Comments
Keywords
ASCII chart
Escape sequences
History of C++
Flow control
Conditional execution statements
Iteration statements
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
throw expression
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

Signals an erroneous condition and executes an error handler.

Contents

[edit] Syntax

throw expression (1)
throw (2)

[edit] Explanation

See try-catch block for more information about try and catch (exception handler) blocks

Exceptions are used to signal erroneous or unusual conditions when they occur during execution. The act of signaling such an exceptional condition is called throwing an exception and is achieved with the syntax presented above and explained below. The act of responding to an exception that was thrown is called catching an exception or exception-handling, and is done with a try-catch block. The overall usage of exceptions (throwing and catching) is called exception mechanisms.

Executing a throw expression (as of syntax (1)) stops the normal flow of the program (note that the type of the expression must not be void). The control flow works backwards from the throwing-site, destroying any stack-based object with automatic storage duration in a process called stack unwinding, until it reaches the start of a try block, at which point the arguments of the corresponding catch blocks are compared with the thrown expression to find a match. If no match is found, the control flow continues to unwind the stack until the next try block, and so on. If a match is found, the control flow jumps to the matching catch block, usually called the exception handler. The exception handler executes code in response to the exception that occurred.

Executing a throw (as of syntax (2)) within an exception handler has the effect of re-throwing the exception object that was caught by the exception handler.

Several erroneous situations can arise during handling of an exception:

  • If no appropriate exception handler is found (no exception handlers in the call stack accept the parameter passed to the throw expression), std::terminate() is called.
  • If during stack unwinding any of the destructors exit via an exception (second exception is thrown when the handling of current exception is unfinished), std::terminate() is called.

[edit] Common Usage

Throwing an exception is commonly used to report an exceptional condition that deviates from the normal courses of action of the program, colloquially referred to as the "good execution path". The C++ standard library provides a number of exception classes that can be used for common exceptions, but anything can be throw as an exception, although it is generally recommended, when creating custom exceptions, to derive them from the base-class std::exception.

Typical usage examples include, but certainly not limited to:

  • Being unable to load, read, or write to a file.
  • Finding a variable's value to be outside its valid range (e.g. an index past the length of an array). (See std::out_of_range)
  • Detecting bad numerical conditioning, a singularity, or overflowing / underflowing variables.
  • Being unable to connect to a peripheral or network.

Exceptions are often misused or their purpose is mistaken. Here are some important usage remarks:

  • Exceptions are not suitable for fatal-error reports, although one can throw exceptions which will never be handled, and thus, cause a complete unwinding of the stack until the program is terminated. If the only appropriate response to a given error-condition is to terminate immediately, one should do so directly with either std::terminate() or other program halting methods.
  • Exceptions are not to be confused with assert. Asserts can be used to check a number of conditions that should be valid (i.e. assertions) when the application reaches a given point of execution. Assertions only produce executable code when compiled in debugging mode, and are thus meant to be used for pedantic checks that verify the integrity of the variables and the general state of the program during debugging. Because these pedantic checks are usually only necessary in initial debugging phases (after which the correctness of the program has been established) and because evaluating all these assertions is expensive at run-time, they should not appear in the released programs. Errors whose root cause is most certainly an error in the program's code should be verified with assert and rooted-out during debugging. Exceptions are used mostly to detect errors that are not caused by an erroneous program but by erroneous data, ill-conditioned problems, missing files, invalid configurations, insufficient memory, etc., which are all problems that any "correct" program or algorithm could have.
  • Exceptions are meant to branch out of the "good" path of execution, they should not be used as a substitute for other branching mechanisms (like if-statements and switch-cases). Not only is it generally verbose to use exceptions where a simple if-statement would suffice, it is also wasteful since stack-unwinding is generally not needed. Furthermore, exception-handling is a special channel for reporting exceptional situations only: the presumption here is that the vast majority of the time that a given function is executed, no exceptions are thrown. Using exceptions to signal frequently occurring situations is generally considered an abuse of exception mechanisms.

[edit] Keywords

throw

[edit] Example

[edit] See also