Home >Backend Development >C++ >How to divide the exception hierarchy in C++ function exception handling?
The exception hierarchy in C provides different inheritance levels of exception classes for classifying exceptions. This hierarchy is rooted at the std::exception class and includes base exceptions, runtime exceptions, and logical exceptions. More specific exception classes are derived from these base classes. Through the exception handling mechanism, exceptions at different levels can be caught and corresponding measures taken as needed.
Exception hierarchy in C function exception handling
In C, function exception handling can be reported by throwing an exception object abnormal situation. In order to classify different exceptions, C introduces an exception hierarchy. The exception hierarchy is an inheritance hierarchy of exception classes defined by the standard library that provides different levels of information for exception objects.
1. Exception class inheritance hierarchy
The exception hierarchy is the inheritance hierarchy rooted at the std::exception
class:
class std::exception { public: virtual ~exception() noexcept = default; virtual const char* what() const noexcept = 0; }; // 基本异常类 class std::runtime_error : public std::exception { public: runtime_error(const char* whatArg) : whatArg_(whatArg) {} virtual const char* what() const noexcept override { return whatArg_; } private: const char* whatArg_; }; // 派生异常类 class std::logic_error : public std::runtime_error { public: logic_error(const char* whatArg) : runtime_error(whatArg) {} };
2. Exception hierarchy division
Exception hierarchy divides exception classes into different levels:
More specific exception classes are derived from std::runtime_error
and std::logic_error
, for example:
std::bad_alloc
: Memory allocation failed. std::invalid_argument
: Invalid parameter. std::range_error
: Range error (for example, array subscript out of bounds). 3. Practical case
Consider the following function:
int divide(int numerator, int denominator) { if (denominator == 0) { throw std::invalid_argument("denominator cannot be zero"); } return numerator / denominator; }
When denominator
is 0, this function Throws std::invalid_argument
exception. This exception belongs to the std::logic_error
level and represents an invalid parameter error in the program logic.
When calling the divide
function, you can use the exception handling mechanism to catch exceptions:
try { int result = divide(10, 2); std::cout << "Result: " << result << std::endl; } catch (const std::invalid_argument& e) { std::cerr << "Error: " << e.what() << std::endl; }
In this case, when denominator
is When 0, the std::invalid_argument
exception will be caught and an error message printed.
The above is the detailed content of How to divide the exception hierarchy in C++ function exception handling?. For more information, please follow other related articles on the PHP Chinese website!