Home > Backend Development > C++ > body text

How to define the exception class in C++ function exception handling?

WBOY
Release: 2024-04-15 21:45:01
Original
1087 people have browsed it

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.

C++ 函数异常处理中的异常类如何定义?

Exception class definition in C function exception handling

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_;
};
Copy after login

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.

Practical case

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template