Exception Handling
Open in the Padhaiko app9.1 Basics of exception handling
An exception is an abnormal run-time condition (division by zero, failure to open a file, an invalid argument, no memory). Exception handling is the C++ mechanism that separates the code that detects an error from the code that handles it. Three keywords are used:
| Keyword | Meaning |
|---|---|
try | Block of code in which exceptions may be thrown and monitored |
throw | Raises (signals) an exception; control leaves the current function |
catch | Handler that receives and processes an exception of a given type |
9.2 Advantage over conventional error handling
In conventional error handling a function returns an error code (such as -1) or sets a global flag, and every caller must test it. It is easy to forget the test, the code is cluttered with if statements, constructors cannot return a value, and the real result and the error share the same return value.
| Feature | Return codes / flags | Exceptions |
|---|---|---|
| Checking | Every caller must test, easy to ignore | An unhandled exception cannot be ignored silently (terminate) |
| Code layout | Normal code and error code mixed | Normal code in try, errors in catch |
| Error information | One integer | Any object, with data and a message |
| Propagation | Passed manually up each level | Automatic through the call stack |
| Constructors | Cannot return a code | Can throw |
| Clean-up | Manual | Destructors run during unwinding |
9.3 Exception handling mechanism
When a throw statement runs, C++ creates the exception object, leaves the current block and searches the enclosing try blocks for a catch handler whose parameter type matches. While leaving each function the local objects are destroyed (stack unwinding). If a handler is found it runs and then execution continues after the whole try-catch block; the program does not return to the throw point. If no handler is found anywhere, the program calls terminate().
#include <iostream>
using namespace std;
double divide(double a, double b) {
if (b == 0)
throw "Division by zero"; // throw a C-string
return a / b;
}
int main() {
double x = 10, y = 4;
try {
cout << "10 / 4 = " << divide(x, y) << endl;
double r = divide(x, 0); // throws here
cout << "10 / 0 = " << r << endl;
cout << "this line is skipped" << endl;
}
catch (const char *msg) {
cout << "Error caught: " << msg << endl;
}
cout << "program continues" << endl;
return 0;
}10 / 4 = 2.5
Error caught: Division by zero
program continuesThe statements after the throwing call inside the try block are skipped, and the program continues after the handler.
9.4 Multiple handlers
A try block can be followed by several catch blocks, one for each exception type. They are tried in order and the first matching handler runs, so a handler for a derived class must come before the handler for its base class. A match is an exact type (with only a few conversions: derived to base, adding const); an int handler does not catch a double or a char.
9.5 Catching all exceptions
catch (...) (three dots) is the catch-all handler: it catches an exception of any type but gives no access to the object. It must be the last handler.
#include <iostream>
#include <string>
using namespace std;
void test(int choice) {
try {
if (choice == 1) throw 42; // int
if (choice == 2) throw 3.14; // double
if (choice == 3) throw string("text error"); // string object
if (choice == 4) throw 'x'; // char
cout << "choice " << choice << ": no exception" << endl;
}
catch (int e) { cout << "choice " << choice << ": int " << e << endl; }
catch (double e) { cout << "choice " << choice << ": double " << e << endl; }
catch (const string &e) { cout << "choice " << choice << ": string " << e << endl; }
catch (...) { cout << "choice " << choice << ": some other exception" << endl; }
}
int main() {
for (int i = 1; i <= 5; i++) test(i);
return 0;
}choice 1: int 42
choice 2: double 3.14
choice 3: string text error
choice 4: some other exception
choice 5: no exceptionThe thrown char has no matching handler, so the catch-all runs.
9.6 Rethrowing exception
A handler that cannot fully deal with an exception may do local clean-up and then pass it on by writing throw; with no operand. The same exception object is rethrown to the next outer try block.
#include <iostream>
using namespace std;
void inner() {
try {
throw 7;
}
catch (int e) {
cout << "inner(): caught " << e << ", doing local clean-up, rethrowing" << endl;
throw; // pass the same exception outward
}
}
int main() {
try {
inner();
cout << "not reached" << endl;
}
catch (int e) {
cout << "main(): caught " << e << " again" << endl;
}
return 0;
}inner(): caught 7, doing local clean-up, rethrowing
main(): caught 7 again9.7 Exception with arguments
The thrown object can be an object of a class that carries information (an error code, a message, the bad value). The handler receives it by value or, better, by const reference. User classes may be derived from the standard class std::exception, which has the virtual function what() that returns a message.
#include <iostream>
#include <string>
#include <exception>
using namespace std;
class BankError {
int code;
string message;
public:
BankError(int c, const string &m) : code(c), message(m) {}
int getCode() const { return code; }
string getMessage() const { return message; }
};
class Account {
double balance;
public:
Account(double b) : balance(b) {}
void withdraw(double amount) {
if (amount > balance)
throw BankError(101, "Insufficient balance: short by " + to_string(amount - balance));
balance -= amount;
}
double getBalance() const { return balance; }
};
class RangeError : public exception { // derived from the standard base class
public:
const char *what() const noexcept override { return "value out of range"; }
};
int main() {
Account acc(500);
try {
acc.withdraw(200);
cout << "balance = " << acc.getBalance() << endl;
acc.withdraw(400);
}
catch (const BankError &e) {
cout << "Error " << e.getCode() << ": " << e.getMessage() << endl;
}
try {
throw RangeError();
}
catch (const exception &e) {
cout << "standard exception: " << e.what() << endl;
}
return 0;
}balance = 300
Error 101: Insufficient balance: short by 100.000000
standard exception: value out of rangeStandard exceptions in <stdexcept> include runtime_error, logic_error, out_of_range, invalid_argument, and bad_alloc (from new) and bad_cast (from dynamic_cast).
9.8 Exceptions specification for function
An exception specification lists the types a function may throw. The old form was
void f() throw(int, double); // f may throw only int or double
void g() throw(); // g throws nothingThis throw(...) form is deprecated in C++11 and removed in C++17, so a modern compiler does not accept it. Its replacement is noexcept: void g() noexcept; promises that g throws nothing, and if it throws anyway the program calls std::terminate() immediately.
9.9 Exceptions in constructors and destructors
A constructor can throw an exception, which is the standard way to report that an object could not be built. If the exception leaves the constructor, the object is not created and its destructor does not run, but the members and base classes that were already constructed are destroyed in reverse order, so no resources leak if they are held by objects.
A destructor must not let an exception escape, because destructors also run during stack unwinding, and a second exception during unwinding calls terminate(). Destructors are noexcept by default; handle errors inside them.
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
class Resource {
string name;
public:
Resource(const string &n) : name(n) { cout << " acquire " << name << endl; }
~Resource() { cout << " release " << name << endl; }
};
class Widget {
Resource r1;
Resource r2;
public:
Widget(bool fail) : r1("first"), r2("second") {
cout << " Widget body starts" << endl;
if (fail) throw runtime_error("constructor failed");
cout << " Widget constructed" << endl;
}
~Widget() { cout << " Widget destructor" << endl; }
};
void work() {
Resource local("local in work()");
throw 1; // the stack is unwound: local is destroyed
}
int main() {
cout << "stack unwinding:" << endl;
try { work(); }
catch (int) { cout << " caught in main" << endl; }
cout << "constructor throws:" << endl;
try { Widget w(true); }
catch (const exception &e) { cout << " caught: " << e.what() << endl; }
cout << "constructor succeeds:" << endl;
{ Widget w(false); }
return 0;
}stack unwinding:
acquire local in work()
release local in work()
caught in main
constructor throws:
acquire first
acquire second
Widget body starts
release second
release first
caught: constructor failed
constructor succeeds:
acquire first
acquire second
Widget body starts
Widget constructed
Widget destructor
release second
release first9.10 Handling uncaught exceptions
If an exception is thrown and no handler matches, C++ calls std::terminate(), which by default calls abort() and ends the program abnormally. The function set_terminate() installs a custom handler that can write a message and must end the program (it must not return).
#include <iostream>
#include <exception>
#include <cstdlib>
using namespace std;
void myTerminate() {
cout << "custom terminate handler: an exception was not handled" << endl;
exit(1); // a terminate handler must not return
}
void safe() noexcept { cout << "safe() promises not to throw" << endl; }
int main() {
set_terminate(myTerminate);
safe();
cout << "about to throw an exception with no handler" << endl;
throw 99; // nobody catches it
cout << "never printed" << endl;
return 0;
}safe() promises not to throw
about to throw an exception with no handler
custom terminate handler: an exception was not handledThe program stops at the throw, so "never printed" does not appear, and the exit status of this run is 1.
9.11 Handling unexpected exception
In the old language, if a function with a throw(...) specification threw a type that was not in its list, the function std::unexpected() was called, which called terminate() by default. A custom handler could be set with set_unexpected().
void myUnexpected() { cout << "unexpected exception"; exit(1); }
set_unexpected(myUnexpected);
void f() throw(int) { throw 'x'; } // char is not allowed: unexpected() is calledBoth unexpected() and set_unexpected() were removed in C++17. In modern code the same situation is handled by noexcept (a violation calls terminate(), as in section 9.10) and by set_terminate().
Worked Examples
1
Trace the program of section 9.3 and state what would change if the throw is replaced by a normal return -1 error code.
Normal path. divide(10, 4) returns 2.5 and the first line prints 10 / 4 = 2.5.
Exception path. divide(10, 0) finds b == 0 and executes throw "Division by zero". The function ends at once, control passes to the first catch whose type is const char *, which prints Error caught: Division by zero. The two statements after the call (cout << "10 / 0 = " ... and the "skipped" line) are never executed.
After the handler. Execution resumes after the catch block, so program continues is printed.
With a return code. return -1 is also a valid division result in general, so the caller cannot tell an error from a real answer, and every call must be followed by a test. With the exception the normal code stays clean and the error cannot be ignored.
Output: 10 / 4 = 2.5, Error caught: Division by zero, program continues.
2
For the program of section 9.5 (test(1) to test(5)), give the output and explain why the char case reaches catch (...).
Matching. throw 42 matches catch (int); throw 3.14 matches catch (double); throw string("text error") matches catch (const string &). No exception occurs for 5, so the try block finishes normally.
The char case. throw 'x' throws a char. There is no catch (char), and C++ does not convert char to int for matching a handler, so the handlers for int, double and string are skipped and catch (...) runs.
choice 1: int 42; choice 2: double 3.14; choice 3: string text error; choice 4: some other exception; choice 5: no exception.
3
A class Widget has two members r1 and r2 of class Resource. Its constructor throws when it is called with true. Give the order of messages and explain which destructors run.
Construction order. The members are constructed in the order of declaration, r1 ("first") then r2 ("second"), before the body of the constructor starts. The body prints Widget body starts and then throws.
What is destroyed. The Widget object was never completed, so ~Widget() does not run. The two fully built members are destroyed in the reverse order of construction: second is released first, then first. The handler in main then prints caught: constructor failed.
Successful case. When the constructor does not throw, the destruction order is ~Widget() first and then the members in reverse order (second, first). The program output in section 9.9 shows both cases.
Failed construction: acquire first, acquire second, body starts, release second, release first, caught (no Widget destructor). Successful: Widget destructor, then release second, release first.
Exercises
Exercises: Exception Handling
Write a program with a class Account that throws a BankError object (code and message) when the withdrawal is larger than the balance. Use an initial balance of 500, withdraw 200 and then 400, and show the output.
Program.
#include <iostream>
#include <string>
#include <exception>
using namespace std;
class BankError {
int code;
string message;
public:
BankError(int c, const string &m) : code(c), message(m) {}
int getCode() const { return code; }
string getMessage() const { return message; }
};
class Account {
double balance;
public:
Account(double b) : balance(b) {}
void withdraw(double amount) {
if (amount > balance)
throw BankError(101, "Insufficient balance: short by " + to_string(amount - balance));
balance -= amount;
}
double getBalance() const { return balance; }
};
class RangeError : public exception { // derived from the standard base class
public:
const char *what() const noexcept override { return "value out of range"; }
};
int main() {
Account acc(500);
try {
acc.withdraw(200);
cout << "balance = " << acc.getBalance() << endl;
acc.withdraw(400);
}
catch (const BankError &e) {
cout << "Error " << e.getCode() << ": " << e.getMessage() << endl;
}
try {
throw RangeError();
}
catch (const exception &e) {
cout << "standard exception: " << e.what() << endl;
}
return 0;
}Output. After the first withdrawal the balance is 500 - 200 = 300. The second request of 400 is 100 more than the balance, so BankError(101, ...) is thrown and caught by the const BankError & handler.
balance = 300
Error 101: Insufficient balance: short by 100.000000
standard exception: value out of rangebalance = 300, then Error 101: Insufficient balance: short by 100.000000
Why must handlers for derived exception classes come before handlers for their base class? Give an example with exception and RangeError.
A handler for a base class also matches objects of every derived class. Handlers are tried in order, so a base handler placed first would catch everything and the derived handler after it could never run (compilers warn about this).
With catch (const RangeError &e) placed before catch (const exception &e), a RangeError is handled specifically and any other standard exception falls to the general handler. If the order is reversed, the RangeError is caught by the exception handler first.
Derived handler first, base handler last; otherwise the base handler catches the derived objects too.
What does throw; do and where is it legal? Show it with the program of section 9.6 and give the output.
throw; with no operand rethrows the exception currently being handled; it is legal only inside a catch block (or a function called from one). The original object is passed on unchanged, so an outer handler sees the same type and value.
In the program, inner() throws 7, its handler prints the first line and rethrows, and main catches the same 7:
inner(): caught 7, doing local clean-up, rethrowing
main(): caught 7 againinner(): caught 7, doing local clean-up, rethrowing; then main(): caught 7 again.
What is the difference between throw(int) and noexcept? Why does the program of section 9.10 end with exit status 1, and what happens to the statement after throw 99;?
throw(int) was the old exception specification, which listed the allowed types and was checked at run time through unexpected(); it is removed in C++17. noexcept only says whether a function may throw at all; breaking the promise calls terminate().
throw 99; in main has no handler, so terminate() runs. The installed handler prints its message and calls exit(1), which gives the exit status 1. The statement after the throw is never reached.
noexcept replaces throw(). The uncaught throw calls the custom terminate handler, which exits with status 1; the later statement is not executed.
Why should a destructor never throw an exception? What happens during stack unwinding if it does?
Destructors are called automatically when an exception is being propagated and local objects are destroyed (stack unwinding). If one of those destructors throws a new exception while the first is still active, C++ has two exceptions at once and cannot choose, so it calls std::terminate() and the program ends.
Therefore all errors inside a destructor must be handled inside it with its own try and catch. Destructors are noexcept by default since C++11, so an escaping exception ends the program at once.
An exception leaving a destructor during unwinding causes terminate(); catch and handle errors inside the destructor.