In C++, why does catch (const ParseError&) never run after catch (const std::runtime_error&) when ParseError derives from runtime_error?
answer
- first match, not best match
- a base handler matches derived types
- order of appearance
- catch-all goes last
basics
~20 sC++ tries a try block's handlers in order of appearance and takes the first that matches, not the best match. A handler for a public base matches every derived exception, so a later derived-class handler is unreachable; order handlers most-derived first.
solid answer
~40 sHandler selection is not overload resolution. The runtime walks the `catch` clauses top to bottom and stops at the first one whose type is the thrown type or an unambiguous public base of it. Because `ParseError` derives publicly from `std::runtime_error`, `catch (const std::runtime_error&)` matches first and `catch (const ParseError&)` below it is dead code. Clang warns: `exception of type 'const ParseError &' will be caught by earlier handler [-Wexceptions]`. The fix is to order from most derived to most general, with `catch (...)`, if present, last; clang rejects a catch-all that is not last. Matching also applies no conversions beyond derived-to-base and pointer conversions, so `throw 42;` does not match `catch (long)`.
code
cpp · 19 lines#include <iostream>
#include <stdexcept>
#include <string>
struct ParseError : std::runtime_error {
using std::runtime_error::runtime_error;
};
void import_file() { throw ParseError("bad header"); }
int main() {
try {
import_file();
} catch (const std::runtime_error& e) {
std::cout << "runtime_error handler: " << e.what() << '\n';
} catch (const ParseError& e) { // never reached
std::cout << "ParseError handler: " << e.what() << '\n';
}
}go deeper
Know that handlers are tried top to bottom, that the first match wins, and that catch (...) goes last.
Explain the matching rules exactly: same type, unambiguous public base, or pointer conversions, and nothing else, which is why literals and integers surprise people.
Diagnose swallowed specific errors by reading the handler chain and the -Wexceptions output, and restructure handlers so each level catches only what it can act on.
Keep the team's exception hierarchy shallow and documented so handler order stays obvious, and make unreachable-handler warnings fail the build.
## The rule When an exception leaves a `try` block, C++ looks at that block's handlers **in order of appearance** and activates the **first one that matches**. There is no ranking: a more specific handler further down does not win over a general one above it. The standard even notes that this makes it possible to write handlers that can never be executed, such as a handler for a derived class placed after a handler for its base. A handler `catch (T)` or `catch (T&)` (with any cv-qualification) matches an exception object of type `E` when: - `T` and `E` are the same type, ignoring top-level cv-qualifiers; or - `T` is an **unambiguous public base class** of `E`; or - both are pointer (or pointer-to-member) types and `E` converts to `T` by a standard pointer conversion, a function pointer conversion or a qualification conversion; or `E` is `std::nullptr_t` and `T` is a pointer type. Nothing else converts. No user-defined conversion, no integral promotion, no `int` to `long`. ## The importer's bug Picture an importer whose parser throws `ParseError`, publicly derived from `std::runtime_error`, and whose I/O layer throws `std::system_error`, which also derives from `std::runtime_error`. The calling code was written with the general handler first: ```cpp try { import_file(path); } catch (const std::runtime_error& e) { // matches ParseError and system_error report_generic(e); } catch (const ParseError& e) { // unreachable report_line(e); } ``` Every `ParseError` lands in the first handler, so the line-number report never appears. Clang diagnoses it under `-Wexceptions`, which in the run below fired even with no warning flags at all: ```plaintext warning: exception of type 'const ParseError &' will be caught by earlier handler [-Wexceptions] note: for type 'const std::runtime_error &' ``` ## Ordering handlers correctly 1. **Most derived first**: `ParseError`, then other specific types. 2. **Then intermediate bases**: `std::system_error`, then `std::runtime_error`. 3. **Then `const std::exception&`** for anything from the standard hierarchy. 4. **Finally `catch (...)`**, which matches any exception. The standard requires it to be the last handler of its `try` block, and clang rejects the program otherwise with `error: catch-all handler must come last`. If no handler in this `try` block matches, the search continues in the dynamically enclosing `try` blocks of the same thread; if none matches anywhere, `std::terminate` is called. ## Matching surprises worth knowing | Thrown | Handler | Matches? | Why | |---|---|---|---| | `throw 42;` | `catch (long)` | no | no arithmetic conversion in matching | | `throw "bad header";` | `catch (const std::string&)` | no | the object is a `const char*`; no user-defined conversion | | `throw "bad header";` | `catch (const char*)` | yes | same type after array-to-pointer conversion | | a type with a private `std::exception` base | `catch (const std::exception&)` | no | the base must be public | | `ParseError` | `catch (const std::runtime_error&)` | yes | public base | The string-literal row is a classic: code that throws literals for quick error messages is invisible to every `std::string` and `std::exception` handler, and falls through to `catch (...)` or to `std::terminate`. ## Handler search across functions Ordering matters inside one `try` block, but the search does not stop there. If no handler of the innermost `try` block matches, the search continues in the dynamically enclosing `try` blocks, which usually live in callers further up the stack. That gives a second ordering axis: - A **specific** handler deep in the importer catches only `ParseError` and recovers by skipping the bad record. - A **general** handler at the top of the command loop catches `const std::exception&` and reports the failure. - A `catch (...)` at the very top of `main` and of each thread function makes sure nothing reaches `std::terminate` unreported. If the deep handler instead catches `const std::exception&`, it swallows I/O errors that the top level should have seen, which is the same bug as the misordered handlers, spread over two functions. ## Design notes for a handler chain - Keep exception hierarchies shallow so the correct order is obvious. - Catch only the types you can act on at this level; let the rest propagate. - Treat a `-Wexceptions` warning as an error: an unreachable handler is always a bug.
- Why does throw "bad header"; slip past a catch (const std::string&) handler?The operand undergoes array-to-pointer conversion, so the exception object is a `const char*`. Handler matching allows derived-to-base and certain pointer conversions only; it never applies a user-defined conversion such as `std::string`'s converting constructor. Only `catch (const char*)` or `catch (...)` sees it. Throwing a class derived from `std::exception` avoids the problem.
- What happens when no handler in any enclosing try block matches?`std::terminate` is called. Whether the stack is unwound first, running destructors of local objects, is implementation-defined; in a run with Apple clang and libc++, a local's destructor did not run. Code that relies on destructors to flush state must catch at the top of `main` and of each thread function.
- C++ picks the most specific matching handler, like overload resolution.
- A catch (long) handler catches throw 42; through integral conversion.
- catch (...) can go anywhere in the handler list.
- catch (const std::string&) catches a thrown string literal.