首页 > 文章列表 > C++ 函数异常处理中的异常类如何定义?

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

异常处理 异常类
273 2024-04-23

C++ 中定义异常类:需从 std::exception 派生新类,重写 what 虚函数提供异常消息;如例所示,MyException 类重写 what 返回异常消息。实战案例中,divide 函数抛出 std::runtime_error 异常,main 函数捕获并打印异常消息。

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

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

在 C++ 中,异常类是用来处理函数异常情况的。要定义一个异常类,需要从 std::exception 类派生一个新类,并重写 what 虚函数以提供异常消息。

以下是一个定义异常类的示例:

#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_;
};

在这个示例中,MyException 类从 std::exception 类派生,并重写了 what 函数以返回异常消息。消息可以在构造函数中设置。

实战案例

以下是一个使用异常类的函数的示例:

#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;
}

在上述示例中,divide 函数在除数为零时抛出一个 std::runtime_error 异常。main 函数使用 try-catch 块捕获异常并打印异常消息。