Notes and Examples on Exceptions

base class

include <stdexcept>
namespace std
___{
______class logic_error; // : public exception
________class domain_error; // : public logic_error
________class invalid_argument; // : public logic_error
________class length_error; // : public logic_error
________class out_of_range; // : public logic_error
_____class runtime_error; // : public exception
________class range_error; // : public runtime_error
________class overflow_error; // : public runtime_error
________class underflow_error; // : public runtime_error
___}

children of exception

children of logic_error

children of runtime_error

Unrelated Exceptions

bad_alloc thrown by new on allocation failure
bad_cast thrown by dynamic_cast when fails with a referenced type
bad_exception thrown when an exception type doesn't match any catch
bad_typeid thrown by typeid

io_base::failure

This is an unusual type of exception. It is an inner class, of the class io_base. The idea is that normally, a failure only occurs when an object of type io_base, has created that failure. failure is also a child of std::exception. So the decleration of failure looks like:
namespace std { class io_base { class failure : public std::exception {

ParentChildException.cpp demonstrates how to use dynamic_cast to determine if two classes are related. The relationship between most of the standard exceptions is demonstrated. A template function, TestInheritance, uses the dynamic cast operator to try to convert a pointer of two different exception types to one another. An upcast, returns a valid pointer. A downcast, or a cast to an unrelated type, returns a null. This program also shows how to get access to protected members of a class:

class hack_ios_base : protected ios_base {
public:
___hack_ios_base() {}

___static ios_base::failure FAIL;
};

ios_base::failure hack_ios_base::FAIL( "failure");

NestedClass.cpp is a trivial program which calls a constructor for a nested class, outside of the containing class. This was used as the template to write the code for hack_ios_base.

exception.cpp illustrates recasting of exceptions, and the set_unexpected function.

exception_what.cpcp illustrates calls to what

StrangeThrow.cpp test out trying throw(...) and it doesn't work. It also demonstrates that it is possible to use throw() in a creator.

Botch.cpp shows why it is a design mistake to throw an exception from a destructor, the stack can't unwind, because it causes two throws, while the program is designed to handle only one

exception_constructor.cpp Shows how constructors are called for thrown objects

bad_typeid.cpp shows how calling typeid on a null pointer causes an exception