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.


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

Runtime Errors

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

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.

Posted: May 15th, 2014 at 11:22 am
Last Updated on: June 11th, 2017 at 12:28 pm