C++ stdexcept Library
C++ stdexcept Classes
The <stdexcept> library has classes for common errors (exceptions). When something goes wrong, you throw an object of one of these classes, with a message that describes the error. Then you catch it, and use what() to get the message. The classes are in two groups:
- Logic errors are mistakes in the program itself, like using an index that is too big, or a value that breaks a rule. You can find them by checking the values before you use them.
- Runtime errors are problems that happen while the program runs, often because of something outside the program, like a missing file, or a result that is too big to store.
All the classes come from the exception class in the <exception> header. Catch exception to handle all of them in one place. Always catch an exception by reference (with &).
Logic Errors
| Name | Description |
|---|---|
| logic_error | Reports a mistake in the logic of the program. It is the parent class of all logic errors |
| domain_error | Reports that a value is outside the values that a math function works for |
| invalid_argument | Reports that a value is not valid, like a negative age |
| length_error | Reports that something would get longer than its maximum allowed length |
| out_of_range | Reports that a value, like an index, is outside the allowed range |
Runtime Errors
| Name | Description |
|---|---|
| runtime_error | Reports a problem that happens while the program runs. It is the parent class of all runtime errors |
| overflow_error | Reports that the result of a calculation is too big for its data type |
| range_error | Reports that a result is outside the range of values that its data type can store |
| underflow_error | Reports that the result of a calculation is too small (too close to 0) for its data type |
Base Class (from <exception>)
| Name | Description |
|---|---|
| exception | The parent class of all standard exceptions. Catch it to handle all of them in one place |
| what() | Returns the message of an exception |