Exceptions - C++ Tutorials
Exceptions - C++ Tutorials
Search: Go
Not logged in
C++
Information
Tutorials
Reference
Articles
Forum
Tutorials Exceptions
C++ Language Exceptions provide a way to react to exceptional circumstances (like runtime errors) in programs by transferring control
Ascii Codes to special functions called handlers.
Boolean Operations
Numerical Bases To catch exceptions, a portion of code is placed under exception inspection. This is done by enclosing that portion of
code in a try-block. When an exceptional circumstance arises within that block, an exception is thrown that transfers
C++ Language the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are
Introduction: ignored.
Compilers
Basics of C++: An exception is thrown by using the throw keyword from inside the try block. Exception handlers are declared with the
Structure of a program keyword catch, which must be placed immediately after the try block:
Variables and types
Constants 1 // exceptions An exception occurred. Exception Nr. 20
Operators 2 #include <iostream>
Basic Input/Output
3 using namespace std;
4
Program structure:
5 int main () {
Statements and flow control 6 try
Functions 7 {
Overloads and templates 8 Edit
throw 20;
9 } &
Name visibility
10 catch (int e) Run
Compound data types:
11 {
Arrays
12 cout << "An exception occurred. Exception Nr. " << e << '\n';
Character sequences
13 }
Pointers 14 return 0;
Dynamic memory 15 }
Data structures
Other data types
Classes: The code under exception handling is enclosed in a try block. In this example this code simply throws an exception:
Classes (I)
Classes (II) throw 20;
Special members
Friendship and inheritance
Polymorphism
A throw expression accepts one parameter (in this case the integer value 20), which is passed as an argument to the
Other language features: exception handler.
Type conversions
Exceptions The exception handler is declared with the catch keyword immediately after the closing brace of the try block. The
Preprocessor directives syntax for catch is similar to a regular function with one parameter. The type of this parameter is very important, since
Standard library: the type of the argument passed by the throw expression is checked against it, and only in the case they match, the
Input/output with files exception is caught by that handler.
Multiple handlers (i.e., catch expressions) can be chained; each one with a different parameter type. Only the handler
whose argument type matches the type of the exception specified in the throw statement is executed.
If an ellipsis (...) is used as the parameter of catch, that handler will catch any exception no matter what the type of
the exception thrown. This can be used as a default handler that catches all exceptions not caught by other handlers:
1 try {
2 // code here
3 }
4 catch (int param) { cout << "int exception"; }
5 catch (char param) { cout << "char exception"; }
6 catch (...) { cout << "default exception"; }
In this case, the last handler would catch any exception thrown of a type that is neither int nor char.
After an exception has been handled the program, execution resumes after the try-catch block, not after the throw
statement!.
It is also possible to nest try-catch blocks within more external try blocks. In these cases, we have the possibility that
an internal catch block forwards the exception to its external level. This is done with the expression throw; with no
arguments. For example:
1 try {
2 try {
3 // code here
4 }
5 catch (int n) {
6 throw;
7 }
8 }
9 catch (...) {
10 cout << "Exception occurred";
11 }
Exception specification
Older code may contain dynamic exception specifications. They are now deprecated in C++, but still supported. A
dynamic exception specification follows the declaration of a function, appending a throw specifier to it. For example:
https://www.cplusplus.com/doc/tutorial/exceptions/ 1/3
6/3/2021 Exceptions - C++ Tutorials
This declares a function called myfunction, which takes one argument of type char and returns a value of type double. If
this function throws an exception of some type other than int, the function calls std::unexpected instead of looking for
a handler or calling std::terminate.
If this throw specifier is left empty with no type, this means that std::unexpected is called for any exception. Functions
with no throw specifier (regular functions) never call std::unexpected, but follow the normal path of looking for their
exception handler.
Standard exceptions
The C++ Standard library provides a base class specifically designed to declare objects to be thrown as exceptions. It is
called std::exception and is defined in the <exception> header. This class has a virtual member function called what
that returns a null-terminated character sequence (of type char *) and that can be overwritten in derived classes to
contain some sort of description of the exception.
We have placed a handler that catches exception objects by reference (notice the ampersand & after the type),
therefore this catches also classes derived from exception, like our myex object of type myexception.
All exceptions thrown by components of the C++ Standard library throw exceptions derived from this exception class.
These are:
exception description
bad_alloc thrown by new on allocation failure
bad_cast thrown by dynamic_cast when it fails in a dynamic cast
bad_exception thrown by certain dynamic exception specifiers
bad_typeid thrown by typeid
bad_function_call thrown by empty function objects
bad_weak_ptr thrown by shared_ptr when passed a bad weak_ptr
Also deriving from exception, header <exception> defines two generic exception types that can be inherited by custom
exceptions to report errors:
exception description
logic_error error related to the internal logic of the program
runtime_error error detected during runtime
A typical example where standard exceptions need to be checked for is on memory allocation:
The exception that may be caught by the exception handler in this example is a bad_alloc. Because bad_alloc is
derived from the standard base class exception, it can be caught (capturing by reference, captures all related classes).
Previous: Next:
Type conversions Preprocessor directives
Index
https://www.cplusplus.com/doc/tutorial/exceptions/ 2/3
6/3/2021 Exceptions - C++ Tutorials
https://www.cplusplus.com/doc/tutorial/exceptions/ 3/3