Exception class defined in C: A new class needs to be derived from std::exception and override the what virtual function to provide exception messages; as shown in the example, the MyException class overrides what to return exception messages. In the actual case, the divide function throws a std::runtime_error exception, and the main function captures and prints the exception message.
In C, the exception class is used to handle function exceptions. To define an exception class, derive a new class from the std::exception
class and override the what
virtual function to provide the exception message.
The following is an example of defining an exception class:
#include <exception> class MyException : public std::exception { public: MyException(const char* message) : std::exception(message) {} MyException(const std::string& message) : std::exception(message.c_str()) {} const char* what() const noexcept override { return message_.c_str(); } private: std::string message_; };
In this example, the MyException
class derives from the std::exception
class, and Rewritten the what
function to return an exception message. The message can be set in the constructor.
The following is an example of a function that uses the exception class:
#include <exception> #include <iostream> void divide(int numerator, int denominator) { if (denominator == 0) { throw std::runtime_error("Cannot divide by zero"); } std::cout << "Result: " << numerator / denominator << std::endl; } int main() { try { divide(10, 0); // 抛出异常 } catch (const std::exception& e) { // 捕获异常 std::cerr << "Error: " << e.what() << std::endl; } return 0; }
In the above example, the divide
function operates when the divisor is zero. Throws a std::runtime_error
exception. The main
function uses the try-catch
block to catch exceptions and print the exception message.
The above is the detailed content of How to define the exception class in C++ function exception handling?. For more information, please follow other related articles on the PHP Chinese website!