An exception is an error condition — often outside the program’s direct control — that prevents the program from continuing along its normal execution path. Object creation, file I/O, network operations, and calls into external libraries are all potential sources of exceptions. Robust C++ programs anticipate these failures and handle them gracefully. The Microsoft C++ compiler (MSVC) supports three exception mechanisms: standard C++ exceptions (Documentation Index
Fetch the complete documentation index at: https://mintlify.com/MicrosoftDocs/cpp-docs/llms.txt
Use this file to discover all available pages before exploring further.
try/catch/throw), Windows Structured Exception Handling (SEH), and MFC exceptions. For new C++ code, always prefer standard C++ exception handling — it is type-safe, portable, and guarantees that destructors run during stack unwinding.
Why Exceptions over Error Codes
In C-style programming, errors are typically communicated through return codes or global variables likeerrno. This approach has significant drawbacks: callers can silently ignore error codes, error handling is tangled with normal logic, and intermediate functions must pass codes up the stack even if they have nothing useful to do with them.
C++ exceptions address all of these problems:
- An unhandled exception terminates the program — you cannot silently ignore it
- Exceptions jump directly to the first matching
catchblock, skipping intervening functions - Stack unwinding automatically destroys all local objects (invoking their destructors)
- The code that detects the error is cleanly separated from the code that handles it
Basic try / catch / throw
throw immediately leaves the current scope. The runtime unwinds the stack, calling destructors for all local objects, until it finds a catch block whose parameter type matches the thrown type.
Throw exceptions by value and catch them by const reference. Catching by value causes unnecessary copying (and can slice polymorphic objects). Catching by pointer requires the caller to manage memory.
Catching Multiple Exception Types
catch (...) is a catch-all handler. Place it last — catch blocks are evaluated in order, and the first matching type wins.
Standard Exception Hierarchy
All standard library exceptions derive fromstd::exception, which is defined in <exception>:
std::exception (base)
std::exception (base)
what()— returns a C-string description of the error- All standard exceptions derive from this class
std::logic_error — programming errors detectable before runtime
std::logic_error — programming errors detectable before runtime
Subclasses:
std::invalid_argument— invalid argument passed to a functionstd::domain_error— mathematical domain errorstd::length_error— exceeded maximum allowed sizestd::out_of_range— index or value out of valid range
std::runtime_error — errors detectable only at runtime
std::runtime_error — errors detectable only at runtime
Subclasses:
std::overflow_error— arithmetic overflowstd::underflow_error— arithmetic underflowstd::range_error— result outside representable rangestd::system_error(C++11) — OS-level errors with an error code
std::bad_alloc — memory allocation failure
std::bad_alloc — memory allocation failure
Thrown by
new when memory cannot be allocated.Custom Exception Classes
Derive your own exception classes fromstd::exception or one of its subclasses:
The noexcept Specifier
The noexcept specifier (C++11) declares that a function will not throw any exception. If it does throw, std::terminate is called immediately. Marking move constructors and destructors noexcept enables important optimizations in the Standard Library:
Stack Unwinding and RAII
When an exception propagates through a scope, the C++ runtime unwinds the stack: it calls the destructors of all local objects in reverse order of construction. This guarantees resource cleanup if you use RAII (Resource Acquisition Is Initialization):Exception Specifications (Deprecated)
The oldthrow(type) exception specification syntax (e.g., void f() throw(std::bad_alloc)) is deprecated in C++11 and removed in C++17. Use noexcept or noexcept(false) instead:
Windows Structured Exception Handling (SEH)
Windows provides its own exception mechanism called Structured Exception Handling (SEH), which uses__try, __except, and __finally instead of try/catch. SEH can catch hardware exceptions (access violations, division by zero) that C++ exceptions cannot:
__except filter expression evaluates to one of three constants:
| Constant | Effect |
|---|---|
EXCEPTION_EXECUTE_HANDLER | Handle the exception; execute the __except block |
EXCEPTION_CONTINUE_SEARCH | Pass to the next handler up the stack |
EXCEPTION_CONTINUE_EXECUTION | Resume execution at the faulting instruction |
__finally block runs regardless of whether an exception occurred — similar in purpose to defer in Go or finally in Java:
Comparing C++ Exceptions and SEH
| Feature | C++ Exceptions | Windows SEH |
|---|---|---|
| Standard | ISO C++ | Microsoft/Windows only |
| Portability | Yes | No |
| Catches hardware faults | No | Yes |
| Calls C++ destructors | Yes (always) | Only with /EHa |
| Type-safe | Yes | No |
| Recommended for C++ | ✅ Yes | ❌ Use only for C code or hardware traps |
See Also
- Modern C++ — RAII, smart pointers, and resource management
- Classes and Structs — destructors and Rule of Five
- Basic Concepts — scope and object lifetime