C++ Standard Exceptions

the std::exception class is the base class for all standard exception types provided by the C++ Standard Library. It is part of the <exception> header and serves as a base class from which other exception classes inherit. The std::exception class provides a consistent interface for handling different types of exceptions, making it easier to write robust and error-tolerant programs.

Key Characteristics of std::exception:

Base Class for All Standard Exceptions:

All standard exception types in C++ derive from std::exception. This means that if a particular exception type is thrown, it can be caught as std::exception or as its derived type.

Virtual Member Function: what():

The what() function is a virtual member function that returns a C-style string (const char*). It provides a description of the exception. The default implementation returns a general error message, but derived classes may override it to provide more specific information.

try {
    throw std::exception();
} catch (const std::exception& e) {
    std::cout << "Caught an exception: " << e.what() << std::endl;
}
ExceptionDescription
runtime_errorThis includes all runtime errors
logic_errorThis includes all logical errors
bad_allocOccurs when new cannot request memory
bad_castRelated to dynamic_cast
bad_exceptionIs triggered When the exception handling itself gets problems
bad_typeidError in the context of typeid
ios_base::failureInput or output error

The following error classes are derived from runtime_error:

ExceptionDescription
overflow_errorOverflow in calculations
underflow_errorUnderflow in calculations
range_errorRange overflow. Triggered by the at() function

The following error classes are derived from logic_error:

ExceptionDescription
domain_errorParameter outside the valid range
invalid_argumentInvalid argument
length_errorThe maximum possible size was exceeded during creation
out_of_rangeAccess with illegal index