C++如何生成自定义异常类

   2024-09-30 8020
核心提示:在C++中,您可以通过继承std::exception或其他异常类来创建自定义异常类#includeiostream#includeexception#includestring// 自

在C++中,您可以通过继承std::exception或其他异常类来创建自定义异常类

#include<iostream>#include<exception>#include<string>// 自定义异常类class CustomException : public std::exception {public:    // 构造函数    CustomException(const std::string& message) : message_(message) {}    // 获取异常信息的虚函数    virtual const char* what() const noexcept override {        return message_.c_str();    }private:    std::string message_; // 异常信息};int main() {    try {        throw CustomException("这是一个自定义异常");    } catch (const CustomException& e) {        std::cerr << "捕获到自定义异常: " << e.what()<< std::endl;    }    return 0;}

在这个例子中,我们创建了一个名为CustomException的自定义异常类,它继承自std::exception。我们重写了what()虚函数,以便在抛出异常时提供有关错误的详细信息。在main()函数中,我们使用try-catch语句捕获并处理自定义异常。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号