C++ ยท Chapter 42 of 49

C++ Exceptions

Exceptions provide a way to handle runtime errors gracefully using `try`, `throw`, and `catch` blocks, instead of crashing the whole program. Code that might fail goes in a `try` block; if it throws, control jumps to a matching `catch` block.

The standard library provides exception types like `std::runtime_error` and `std::out_of_range` under `<stdexcept>`, and you can also define your own custom exception classes.

try/throw/catch

`try { ... throw std::runtime_error("oops"); } catch (const std::exception& e) { std::cout << e.what(); }` catches and handles the error using its message.

Custom exceptions

You can throw any type, but it's conventional to derive custom exception classes from `std::exception` and override `what()` to describe the error.

Example 1 (cpp)
try {
    throw std::runtime_error("Something failed");
} catch (const std::exception& e) {
    std::cout << e.what();
}
Output
Something failed

The catch block receives the exception and prints its message via what().

Example 2 (cpp)
try {
    int arr[3] = {1,2,3};
    if (5 >= 3) throw std::out_of_range("bad index");
} catch (const std::out_of_range& e) {
    std::cout << "Caught: " << e.what();
}
Output
Caught: bad index

A specific exception type can be caught and handled distinctly.

Key points

  • try/throw/catch handle runtime errors gracefully.
  • <stdexcept> provides common exception types like runtime_error.
  • catch (const std::exception& e) can catch most standard exceptions.
  • Custom exceptions typically derive from std::exception.
๐Ÿ’ก Note: Uncaught exceptions call std::terminate and crash the program โ€” always catch exceptions you can meaningfully handle.

๐Ÿ“ Quick Quiz

1. Which block contains code that might fail?

2. Which keyword raises an exception?

3. What happens to an uncaught exception?