Standard Exceptions: std::exception, std::runtime_error, etc.
Exception handling is an essential part of programming in C++. Standard exceptions are an important part of the language and provide a consistent approach to handling errors. The two most commonly used standard exceptions are std::exception and std::runtime_error. This guide will explain the purpose and use of standard exceptions, with examples and tips.
What are Standard Exceptions?
Standard exceptions are pre-defined classes that are included in the C++ language. These classes are provided to allow developers to throw exceptions, catch exceptions, and generally handle errors in a consistent and standard way. The two main exceptions are std::exception and std::runtime_error.
std::exception
std::exception is a base class for all standard exceptions. It is used to provide a common interface for catching exceptions. The std::exception class has two functions: what() and what(), which return a description of the exception. Here is an example of how to use it:
try {
// code that might throw an exception
} catch (std::exception& e) {
cout << "Caught exception: " << e.what() << endl;
}
In this example, the code inside the try block might throw an exception. If it does, the catch block will be executed, and the exception will be caught and handled. The exception's description can be accessed using the what() function.
std::runtime_error
std::runtime_error is a derived class of std::exception. It is used to indicate errors that occur during runtime, such as an invalid argument or divide by zero. Here is an example of how to use it:
try {
int a = 5;
int b = 0;
int c = a/b; // this will throw a std::runtime_error
} catch (std::runtime_error& e) {
cout << "Caught runtime error: " << e.what() << endl;
}
In this example, the code inside the try block will throw a std::runtime_error because the value of b is 0. The catch block will be executed, and the exception will be caught and handled.
Tips for Using Standard Exceptions
- Always use standard exceptions for consistency and readability.
- Use the what() function to get the exception's description.
- Catch specific exceptions to better handle errors.
- Be aware of the order of exceptions in your catch blocks.
Standard exceptions are an essential part of programming in C++. They provide a consistent way to handle errors and make code more readable. With the examples and tips provided in this guide, you should now be able to use standard exceptions in your own programs.