Legacy C++ › 5. Exceptions, Strings and I/O
Exceptions
try/catch/throw, stack unwinding and exception specifications.
intermediate #exceptions#try-catch#throw#stack-unwinding#bad_alloc
Explanation
Exceptions report errors without cluttering the normal control flow. throw raises an exception; the runtime unwinds the stack, destroying local objects (calling their destructors) until it finds a matching catch.
- Throw by value, catch by const reference:
catch (const std::exception& e). - Catch handlers are tried in order; put derived types before base types.
catch (...)catches anything.throw;(no operand) rethrows the current exception.- Standard hierarchy (
<stdexcept>):std::exception→logic_error(invalid_argument,out_of_range),runtime_error(overflow_error, …), plusbad_alloc,bad_cast. - Exception specifications (
void f() throw(Foo)) exist in C++98 but are deprecated and removed in C++17. Do not use them. - A destructor must never let an exception escape: during unwinding this calls
std::terminate.
Example
#include <iostream>
#include <stdexcept>
#include <string>
class ParseError : public std::runtime_error {
public:
explicit ParseError(const std::string& m) : std::runtime_error(m) {}
};
struct Guard { // shows unwinding
~Guard() { std::cout << "cleanup\n"; }
};
int parsePositive(const std::string& s) {
Guard g;
if (s.empty()) throw ParseError("empty input");
int v = 0;
for (std::size_t i = 0; i < s.size(); ++i) {
if (s[i] < '0' || s[i] > '9') throw ParseError("bad digit in '" + s + "'");
v = v * 10 + (s[i] - '0');
}
return v;
}
int main() {
try {
std::cout << parsePositive("123") << "\n";
std::cout << parsePositive("12x") << "\n"; // throws
} catch (const ParseError& e) { // most specific first
std::cout << "parse error: " << e.what() << "\n";
} catch (const std::exception& e) {
std::cout << "other: " << e.what() << "\n";
} catch (...) {
std::cout << "unknown\n";
}
return 0;
}
Common pitfalls
catch (std::exception e)(by value) slices the exception. Catch byconst&.- Throwing a pointer (
throw new X) makes cleanup ambiguous. Throw objects. - Raw
new/deletepairs leak when an exception passes between them. Use RAII. - Exceptions thrown from destructors during unwinding terminate the program.
- Do not use exceptions for ordinary control flow; they are slow when thrown.
Legacy vs modern
C++11 adds noexcept (replacing throw()), std::exception_ptr and std::nested_exception. C++23 offers std::expected for exception-free error handling.
Exercises
1. What does throw; inside a catch block do?
It rethrows the original exception object (preserving its dynamic type), unlike throw e; which copies the static type.