Standard Exceptions

Standard Exceptions

The Standard C++ library provides a set of exceptions that are also available for your own use. They also provide a model for how you might construct your own exception hierarchy, perhaps inheriting from a suitable standard library exception class.

exception is the base class for all the Standard C++ library exceptions. It is defined in the header <exception>.

The two main classes derived from exception are logic_error and runtime_error, which are found in  <stdexcept> 

  • The class logic_error represents errors in programming logic, such as passing an invalid argument.
  • Runtime errors are those that occur as the result of unforeseen forces such as hardware failure or memory exhaustion.

Both runtime_error and logic_error provide a constructor that takes a std::string argument so that you can store a message in the exception object and extract it later with exception::what( ) .

A simplified hierarchy looks like this:

  • exception
    • logic_error
      • invalid_argument
      • domain_error
      • length_error
      • out_of_range
    • runtime_error
      • range_error
      • overflow_error
      • underflow_error
    • bad_alloc — thrown to indicate failure to allocate storage
    • bad_cast
    • bad_exception
    • bad_typeid
    • ios_base::failure

… and so on.

The standard library exception classes do not add member functions beyond those provided by exception, but they do define the necessary virtual functions specified in exception.

Thus, you could write code such as:

//
//  main.cpp
//  The Standard C++ Library Exceptions
//
//  Created by Bryan Higgs on 10/8/24.
//

#include <iostream>
#include <exception>

void useStandardLibrary()
{
  // ...
  throw std::bad_exception();
}

int main(int argc, const char * argv[]) 
{
  try
  {
    useStandardLibrary();
  }
  catch (std::exception &e)
  {
    std::cerr << "Standard Library exception "
              << e.what() << std::endl;
  }
  catch (...)
  {
    std::cerr << "Other exception encountered..."
              << std::endl;
  }

  return 0;
}

… which outputs the following:

Standard Library exception std::bad_exception
Program ended with exit code: 0