C++ Standard Library<exception>
In C++ programming, exception handling is an important error handling mechanism that allows a program to handle errors gracefully instead of crashing.
In C++, exception handling is usually implemented using the try, catch, and throw keywords. The standard library provides the std::exception class and its derived classes to handle exceptions.
In the C++ Standard Library,<exception>The header file provides a set of exception handling infrastructure, including exception classes, exception handling mechanisms, and so on.
An exception is an event that occurs during program runtime, which interrupts the normal flow of instructions. In C++, an exception can be an object of any type, but is usually an object of an exception class. The C++ Standard Library defines some basic exception classes, such asstd::exception、std::bad_alloc、std::bad_castetc.
You can extend exception handling functionality by defining your own exception classes, or use existing exception classes from the standard library to handle common exception scenarios.
Syntax
Throw an exception
In C++, the throw keyword is used to throw an exception, with the following syntax:
throw exception_object;
Catch exceptions
Use the try and catch keywords to catch and handle exceptions, with the following syntax:
try {
// 可能抛出异常的代码
} catch (exception_type e) {
// 处理异常的代码
}You can specify the type of exception to catch, or use a generic catch block to catch all types of exceptions:
try {
// 可能会抛出异常的代码
} catch (const std::exception& e) {
// 处理 std::exception 及其派生类的异常
} catch (...) {
// 处理所有其他类型的异常
}
std::exception
std::exception is a base class defined in the C++ standard library and serves as the foundation for all standard exception classes. It defines virtual functions, such as what(), which return a C-style string describing the exception information.
class exception {
public:
virtual const char* what() const noexcept;
};
Standard exception classes
The C++ standard library provides several exception classes derived from std::exception, such as std::runtime_error, std::logic_error, etc., to represent common exception scenarios. You can choose the appropriate class based on the specific exception situation.
throw std::runtime_error("Runtime error occurred");
throw std::logic_error("Logic error occurred");
Example
The following is a use of<exception>A simple example of the header file, demonstrating how to throw and catch exceptions.
Example
#include <exception>
class MyException : public std::exception {
public:
const char* what() const throw() {
return "My custom exception";
}
};
int main() {
try {
// simulate an error condition
bool error_condition = true;
if (error_condition) {
throw MyException();
}
} catch (const std::exception& e) {
std::cout << "Caught an exception: " << e.what() << std::endl;
}
return 0;
}
Output result:
Caught an exception: My custom exception
Exception class
In C++, the standard library provides some common exception classes, all of which inherit fromstd::exception, and can be accessed via#include <stdexcept>Include for use.
The following are some common C++ exception classes and their main purposes:
-
std::exception: The base class for all standard exception classes, defining the basic interface for exceptions. It has a virtual function
what(), used to return a C-style string describing the exception information. -
std::runtime_error: Indicates a runtime error, usually an exception caused by program logic problems, such as invalid arguments, inability to open files, etc.
throw std::runtime_error("Runtime error occurred"); -
std::logic_error: Represents logic errors, usually exceptions caused by program logic errors, such as logical assertion failures and index out of bounds.
throw std::logic_error("Logic error occurred"); -
std::invalid_argument: Indicates that an argument passed to a function is invalid.
throw std::invalid_argument("Invalid argument"); -
std::out_of_range: Indicates accessing an object outside its valid range, such as arrays and containers.
throw std::out_of_range("Out of range"); -
std::overflow_errorandstd::underflow_error: Indicates overflow or underflow in numerical calculations.
throw std::overflow_error("Overflow occurred"); throw std::underflow_error("Underflow occurred"); -
std::bad_alloc: Indicates memory allocation failure.
throw std::bad_alloc(); // 内存分配失败时抛出
Example
#include <new> // include std::bad_alloc exception header file
int main() {
try {
// attempt to allocate a large amount of memory
int* largeArray = new int[1000000000000]; // Simulate memory allocation failure
} catch (const std::bad_alloc& e) {
// Catch std::bad_alloc exception, output error message
std::cerr << "Memory allocation failed: " << e.what() << std::endl;
}
return 0;
}
Output:
Memory allocation failed: std::bad_alloc
Notes
- Exceptions should not be used for normal control flow; they should only be used to handle exceptional situations.
- Exception handling may affect program performance, so it should be used with caution.
- Ensure that
catchHandle all possible exception types in the block to prevent the program from crashing due to unhandled exceptions.
by using<exception>With the header file, C++ programmers can handle error conditions in programs more effectively, improving program robustness and reliability.