DevAcademia lesson/C++ Modern Essentials
C++ Exceptions
Topic progressTopic 101 of 109 - 93% complete
~12 min lesson11 learning blocks2 code examples1 checks/interactions
Lesson outline
What Are Exceptions?
Exceptions let a program signal and handle runtime errors without cluttering normal logic with error codes. You throw an exception where a problem occurs and catch it where you can handle it; the stack unwinds in between, destroying local objects safely (RAII).
Standard Exception Types
The header defines a hierarchy rooted at std::exception. Catch by const reference to avoid slicing and to read .what().
| Type | Header | Typical use |
|---|---|---|
| std::exception | Base of all standard exceptions | |
| std::runtime_error | Errors detectable only at run time | |
| std::logic_error | Programming errors (precondition violations) | |
| std::out_of_range | e.g. vector::at() with a bad index | |
| std::invalid_argument | A function received an invalid value |
Custom Exceptions
Derive your own exception from a standard one so callers can catch it either specifically or as a std::exception.
Was this topic clear?