Exceptions

Overview

Exceptions are a feature supported by C++ but not C.

Note that it is common practise to use e to represent a variable that is of an exception type.

Notation

How The Exceptions Work

The Standard Exceptions

std::exception doesn’t support an additional message (it doesn’t have an e.what()).

The standard exceptions are defined in <stdexcept>. They are split into categories:

Logic Errors

Exception Description
domain_error  
invalid_argument  
length_error  
logic_error  
out_of_range  

Runtime Errors

Exception Description
overflow_error  
range_error  
runtime_error Use std::runtime_error for general errors that occur in the running of your program.
underflow_error  

My Exception Message (e.what() Is Not Saying The Right Thing!

The most common reason for this is that you have forgotten to catch by reference ( &)! Make sure that your catch statement looks like this:

and not like this:

C++11 Additions

C++11 added new exception types to the standard library.

One is the std::system_error. It inherits from std::runtime_error. It is typically thrown by functions which interact with the operating system. It has two members, the standard what(), and a new code(). Calling code() returns the error code associated with the error.

Here is an example:

Notice that the error_code object returns by code() can be inserted into a ostream.

This new system_error object with the additional code() method presents problems when using the standard catch, as other exceptions do not have this method. You can either write two seperate catch statements (my preferred method).

Or you can use a dynamic_cast like below.