Table of Contents

<exception>

<exception> provides the base class std::exception and utilities for exception handling: std::terminate_handler, std::exception_ptr (capture and rethrow exceptions across threads), and std::rethrow_exception.

Most user code catches specific exceptions derived from std::runtime_error or std::logic_error, but this header is essential for implementing exception-safe resource management.

Example

This example throws and catches a runtime exception, accessing its descriptive message via the what() method.

// compile: g++ -std=c++11 -o exceptionexample exceptionexample.cpp
// run: ./exceptionexample
// description: catch and inspect exceptions
 
#include <exception>
#include <iostream>
#include <stdexcept>
 
int main() {
    try {
        throw std::runtime_error("something went wrong");
    } catch (const std::exception& e) {
        std::cout << "caught: " << e.what() << "\n";
    }
 
    return 0;
}