C++ Standard exceptions

In C++, standard exceptions are a set of predefined exception classes defined in the standard library. These exceptions can be used to handle common error scenarios such as out-of-range, division by zero, and bad memory allocation.

The standard exceptions are defined in the <stdexcept> header file and are organized in a hierarchy with a common base class std::exception. The most commonly used standard exceptions include:

  • std::invalid_argument: thrown when an argument is invalid
  • std::out_of_range: thrown when an argument is out of range
  • std::logic_error: thrown when a logical error occurs
  • std::runtime_error: thrown when a runtime error occurs

To handle these exceptions, you can use a try-catch block. For example:

refer to:‮editfigi‬a.com
try {
  // code that might throw an exception
}
catch (const std::invalid_argument& ex) {
  // handle the invalid argument exception
}
catch (const std::out_of_range& ex) {
  // handle the out of range exception
}
catch (const std::exception& ex) {
  // handle other exceptions
}

In this example, the try block contains the code that might throw an exception. If an exception is thrown, the corresponding catch block will be executed to handle the exception. If no exception is thrown or if the exception is not caught by any of the catch blocks, the program will terminate.