Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/language/exceptions"

From cppreference.com
< cpp‎ | language
(Added Spanish language link. Really)
m (std::string::at -> std::basic_string::at.)
 
(15 intermediate revisions by 8 users not shown)
Line 1: Line 1:
 
{{title|Exceptions}}
 
{{title|Exceptions}}
 
{{cpp/language/exceptions/navbar}}
 
{{cpp/language/exceptions/navbar}}
Exception handling provides a way of transferring control and information from some point in the execution of a program to a handler associated with a point previously passed by the execution (in other words, exception handling transfers control up the call stack)
+
Exception handling provides a way of transferring control and information from some point in the execution of a program to a handler associated with a point previously passed by the execution (in other words, exception handling transfers control up the call stack).
  
An exception can be thrown by a {{rlp|throw|throw-expression}}, {{rlp|dynamic_cast}}, {{rlp|typeid}}, {{rlp|new|new-expression}}, [[cpp/memory/new/operator_new|allocation function]], and any of the standard library functions that are specified to throw exceptions to signal certain error conditions (e.g. {{lc|std::vector::at}}, {{lc|std::string::substr}}, etc).
+
Evaluating a {{rlp|throw#throw expressions|{{c/core|throw}} expression}} will thrown an exception. Exceptions can also be thrown in {{rlp|throw|other contexts}}.
  
In order for an exception to be caught, the throw-expression has to be inside a {{rlp|try_catch|try-block}} or inside a function called from a try-block, and there has to be a {{rlp|try_catch|catch clause}} that matches the type of the exception object.
+
In order for an exception to be caught, the {{c/core|throw}} expression has to be inside a {{rlp|try|{{c/core|try}} block}}, and the {{c/core|try}} block has to contain a {{rlp|catch|handler}} that matches the type of the exception object.
  
When declaring a function, {{rlp|except_spec | exception specifications}} and {{rlp|noexcept_spec | noexcept specifiers}} may be provided to limit the types of the exceptions a function may throw.
+
When declaring a function, the following specification(s) may be provided to limit the types of the exceptions a function may throw:
 +
{{rrev|until=c++17|* {{rlp|except spec|dynamic exception specifications}}}}
 +
{{rrev|since=c++11|* {{rlp|noexcept spec|noexcept specifications}}}}
  
 
Errors that arise during exception handling are handled by {{lc|std::terminate}}{{rev inl|until=c++17| and {{lc|std::unexpected}}}}.
 
Errors that arise during exception handling are handled by {{lc|std::terminate}}{{rev inl|until=c++17| and {{lc|std::unexpected}}}}.
  
 
===Usage===
 
===Usage===
 
+
While {{c/core|throw}} expression can be used to transfer control to an arbitrary block of code up the execution stack, for arbitrary reasons (similar to {{lc|std::longjmp}}), its intended usage is error handling.  
While throw-expression can be used to transfer control to an arbitrary block of code up the execution stack, for arbitrary reasons (similar to {{lc|std::longjmp}}), its intended usage is error handling.  
+
  
 
====Error handling====
 
====Error handling====
 
+
Throwing an exception is used to signal errors from functions, where "errors" are typically limited to only the following<ref> H. Sutter (2004) [https://www.drdobbs.com/when-and-how-to-use-exceptions/184401836 "When and How to Use Exceptions"] in Dr. Dobb's</ref><ref>H. Sutter, A. Alexandrescu (2004), "C++ Coding Standards", Item 70</ref><ref>C++ Core Guidelines [https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Ri-except I.10: Use exceptions to signal a failure to perform a required task]</ref>:
Throwing an exception is used to signal errors from functions, where "errors" are typically limited to only the following<ref> H. Sutter (2004) [http://www.drdobbs.com/when-and-how-to-use-exceptions/184401836 "When and How to Use Exceptions"] in Dr. Dobb's</ref><ref>H.Sutter, A. Alexandrescu (2004), "C++ Coding Standards", Item 70</ref><ref>C++ Core Guidelines [https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#i10-use-exceptions-to-signal-a-failure-to-perform-a-required-task I.10]</ref>:
+
# Failures to meet the postconditions, such as failing to produce a valid return value object.
# Failures to meet the postconditions, such as failing to produce a valid return value object
+
# Failures to meet the preconditions of another function that must be called.
# Failures to meet the preconditions of another function that must be called
+
# (for non-private member functions) Failures to (re)establish a class invariant.
# (for non-private member functions) Failures to (re)establish a class invariant
+
  
 
In particular, this implies that the failures of constructors (see also [[cpp/language/raii|RAII]]) and most operators should be reported by throwing exceptions.
 
In particular, this implies that the failures of constructors (see also [[cpp/language/raii|RAII]]) and most operators should be reported by throwing exceptions.
  
In addition, so-called ''wide contract'' functions use exceptions to indicate unacceptable inputs, for example, {{lc|std::string::at}} has no preconditions, but throws an exception to indicate index out of range.
+
In addition, so-called ''wide contract'' functions use exceptions to indicate unacceptable inputs, for example, {{lc|std::basic_string::at}} has no preconditions, but throws an exception to indicate index out of range.
  
 
====Exception safety====
 
====Exception safety====
 +
After the error condition is reported by a function, additional guarantees may be provided with regards to the state of the program. The following four levels of exception guarantee are generally recognized<ref>B. Stroustrup (2000), "The C++ Programming Language" [https://stroustrup.com/3rd_safe.pdf Appendix E]</ref><ref>H. Sutter (2000) "Exceptional C++"</ref><ref>D. Abrahams (2001) [https://www.boost.org/community/exception_safety.html "Exception Safety in Generic Components"]</ref>, which are strict supersets of each other:
  
After the error condition is reported by a function, additional guarantees may be provided with regards to the state of the program. The following four levels of exception guarantee are generally recognized<ref>B. Stroustrup (2000), "The C++ Programming Language"[http://stroustrup.com/3rd_safe.pdf Appendix E"]</ref><ref>H. Sutter (2000) "Exceptional C++"</ref><ref>D. Abrahams (2001) [http://www.boost.org/community/exception_safety.html "Exception Safety in Generic Components"]</ref>, which are strict supersets of each other:
+
# ''Nothrow (or nofail) exception guarantee'' the function never throws exceptions. Nothrow (errors are reported by other means or concealed) is expected of {{rlp|destructor}}s and other functions that may be called during stack unwinding. {{rev inl|since=c++11|The {{rlp|destructor}}s are {{rlpt|noexcept}} by default.}} Nofail (the function always succeeds) is expected of swaps, {{rlp|move constructor}}s, and other functions used by those that provide strong exception guarantee.
 
+
# ''Strong exception guarantee'' If the function throws an exception, the state of the program is rolled back to the state just before the function call (for example, {{lc|std::vector::push_back}}).
# ''Nothrow (or nofail) exception guarantee'' -- the function never throws exceptions. Nothrow (errors are reported by other means or concealed) is expected of {{rlp|destructor}}s and other functions that may be called during stack unwinding. {{rev inl|since=c++11|The {{rlp|destructor}}s are {{rlp|noexcept}} by default.}} Nofail (the function always succeeds) is expected of swaps, {{rlp|move constructor}}s, and other functions used by those that provide strong exception guarantee.
+
# ''Basic exception guarantee'' If the function throws an exception, the program is in a valid state. No resources are leaked, and all objects' invariants are intact.
# ''Strong exception guarantee'' -- If the function throws an exception, the state of the program is rolled back to the state just before the function call. (for example, {{lc|std::vector::push_back}})
+
# ''No exception guarantee'' If the function throws an exception, the program may not be in a valid state: resource leaks, memory corruption, or other invariant-destroying errors may have occurred.
# ''Basic exception guarantee'' -- If the function throws an exception, the program is in a valid state. No resources are leaked, and all objects' invariants are intact.
+
# ''No exception guarantee'' -- If the function throws an exception, the program may not be in a valid state: resource leaks, memory corruption, or other invariant-destroying errors may have occurred.
+
  
 
Generic components may, in addition, offer ''exception-neutral guarantee'': if an exception is thrown from a template parameter (e.g. from the {{tt|Compare}} function object of {{lc|std::sort}} or from the constructor of {{tt|T}} in {{lc|std::make_shared}}), it is propagated, unchanged, to the caller.  
 
Generic components may, in addition, offer ''exception-neutral guarantee'': if an exception is thrown from a template parameter (e.g. from the {{tt|Compare}} function object of {{lc|std::sort}} or from the constructor of {{tt|T}} in {{lc|std::make_shared}}), it is propagated, unchanged, to the caller.  
  
 
===Exception objects===
 
===Exception objects===
 +
While objects of any complete type and cv pointers to {{c/core|void}} may be thrown as exception objects, all standard library functions throw unnamed objects by value, and the types of those objects are derived (directly or indirectly) from {{lc|std::exception}}. User-defined exceptions usually follow this pattern.<ref>D. Abrahams (2001) [https://www.boost.org/community/error_handling.html "Error and Exception Handling"]</ref><ref>isocpp.org Super-FAQ [https://isocpp.org/wiki/faq/exceptions#what-to-throw "What should I throw?"]</ref><ref>C++ Core Guidelines [https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-exception-types E.14: Use purpose-designed user-defined types as exceptions (not built-in types)]</ref>
  
While objects of any complete type and cv pointers to void may be thrown as exception objects, all standard library functions throw anonymous temporary objects by value, and the types of those objects are derived (directly or indirectly) from {{lc|std::exception}}. User-defined exceptions usually follow this pattern.<ref>D. Abrahams (2001) [http://www.boost.org/community/error_handling.html "Error and Exception Handling"]</ref><ref>isocpp.org Super-FAQ [https://isocpp.org/wiki/faq/exceptions#what-to-throw "What should I throw?"]</ref><ref>C++ Core Guidelines [https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e14-use-purpose-designed-user-defined-types-as-exceptions-not-built-in-types E.14]</ref>
+
To avoid unnecessary copying of the exception object and object slicing, the best practice for handlers is to catch by reference.<ref>C++ Core Guidelines [https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-exception-ref E.15: Throw by value, catch exceptions from a hierarchy by reference]</ref><ref>S. Meyers (1996) "More Effective C++" Item 13</ref><ref>isocpp.org Super-FAQ [https://isocpp.org/wiki/faq/exceptions#what-to-catch "What should I catch?"]</ref><ref>H. Sutter, A. Alexandrescu (2004) "C++ Coding Standards" Item 73</ref>
 
+
To avoid unnecessary copying of the exception object and object slicing, the best practice for catch clauses is to catch by reference.<ref>C++ Core Guidelines [https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e15-catch-exceptions-from-a-hierarchy-by-reference E.15]</ref><ref>S. Meyers (1996) "More Effective C++" Item 13</ref><ref>isocpp.org Super-FAQ [https://isocpp.org/wiki/faq/exceptions#what-to-catch "What should I catch?"]</ref><ref>H.Sutter, A. Alexandrescu (2004) "C++ Coding Standards" Item 73</ref>
+
  
===References===
+
===External links===
<references/>
+
{{elink begin}}
 +
{{elink|<references/>}}
 +
{{elink end}}
  
{{langlinks|es|ja|zh}}
+
{{langlinks|es|ja|ru|zh}}

Latest revision as of 05:23, 8 June 2024

 
 
C++ language
General topics
Flow control
Conditional execution statements
if
Iteration statements (loops)
for
range-for (C++11)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications (until C++17*)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
explicit (C++11)
static

Special member functions
Templates
Miscellaneous
 
Exceptions
try block
Throwing exceptions
Handling exceptions
Exception specification
    noexcept specification (C++11)
    dynamic specification (until C++17*)
noexcept operator (C++11)
 

Exception handling provides a way of transferring control and information from some point in the execution of a program to a handler associated with a point previously passed by the execution (in other words, exception handling transfers control up the call stack).

Evaluating a throw expression will thrown an exception. Exceptions can also be thrown in other contexts.

In order for an exception to be caught, the throw expression has to be inside a try block, and the try block has to contain a handler that matches the type of the exception object.

When declaring a function, the following specification(s) may be provided to limit the types of the exceptions a function may throw:

(until C++17)
(since C++11)

Errors that arise during exception handling are handled by std::terminate and std::unexpected(until C++17).

Contents

[edit] Usage

While throw expression can be used to transfer control to an arbitrary block of code up the execution stack, for arbitrary reasons (similar to std::longjmp), its intended usage is error handling.

[edit] Error handling

Throwing an exception is used to signal errors from functions, where "errors" are typically limited to only the following[1][2][3]:

  1. Failures to meet the postconditions, such as failing to produce a valid return value object.
  2. Failures to meet the preconditions of another function that must be called.
  3. (for non-private member functions) Failures to (re)establish a class invariant.

In particular, this implies that the failures of constructors (see also RAII) and most operators should be reported by throwing exceptions.

In addition, so-called wide contract functions use exceptions to indicate unacceptable inputs, for example, std::basic_string::at has no preconditions, but throws an exception to indicate index out of range.

[edit] Exception safety

After the error condition is reported by a function, additional guarantees may be provided with regards to the state of the program. The following four levels of exception guarantee are generally recognized[4][5][6], which are strict supersets of each other:

  1. Nothrow (or nofail) exception guarantee — the function never throws exceptions. Nothrow (errors are reported by other means or concealed) is expected of destructors and other functions that may be called during stack unwinding. The destructors are noexcept by default.(since C++11) Nofail (the function always succeeds) is expected of swaps, move constructors, and other functions used by those that provide strong exception guarantee.
  2. Strong exception guarantee — If the function throws an exception, the state of the program is rolled back to the state just before the function call (for example, std::vector::push_back).
  3. Basic exception guarantee — If the function throws an exception, the program is in a valid state. No resources are leaked, and all objects' invariants are intact.
  4. No exception guarantee — If the function throws an exception, the program may not be in a valid state: resource leaks, memory corruption, or other invariant-destroying errors may have occurred.

Generic components may, in addition, offer exception-neutral guarantee: if an exception is thrown from a template parameter (e.g. from the Compare function object of std::sort or from the constructor of T in std::make_shared), it is propagated, unchanged, to the caller.

[edit] Exception objects

While objects of any complete type and cv pointers to void may be thrown as exception objects, all standard library functions throw unnamed objects by value, and the types of those objects are derived (directly or indirectly) from std::exception. User-defined exceptions usually follow this pattern.[7][8][9]

To avoid unnecessary copying of the exception object and object slicing, the best practice for handlers is to catch by reference.[10][11][12][13]

[edit] External links

 
  1. H. Sutter (2004) "When and How to Use Exceptions" in Dr. Dobb's
  2. H. Sutter, A. Alexandrescu (2004), "C++ Coding Standards", Item 70
  3. C++ Core Guidelines I.10: Use exceptions to signal a failure to perform a required task
  4. B. Stroustrup (2000), "The C++ Programming Language" Appendix E
  5. H. Sutter (2000) "Exceptional C++"
  6. D. Abrahams (2001) "Exception Safety in Generic Components"
  7. D. Abrahams (2001) "Error and Exception Handling"
  8. isocpp.org Super-FAQ "What should I throw?"
  9. C++ Core Guidelines E.14: Use purpose-designed user-defined types as exceptions (not built-in types)
  10. C++ Core Guidelines E.15: Throw by value, catch exceptions from a hierarchy by reference
  11. S. Meyers (1996) "More Effective C++" Item 13
  12. isocpp.org Super-FAQ "What should I catch?"
  13. H. Sutter, A. Alexandrescu (2004) "C++ Coding Standards" Item 73