异常继承

Exception inheritance

本文关键字:继承 异常      更新时间:2023-10-16

是否可能在c++的异常类中有多个元素,我可以将它们与异常关联起来,这样当我抛出它时,用户可以收集更多关于异常的信息,而不仅仅是错误消息?我有下面的类

#include <list>
using namespace std;
class myex : public out_of_range {
private:
    list<int> *li; 
    const char* str = "";
public:
    //myex(const char* err): out_of_range(err) {}
    myex(li<int> *l,const char* s) : li(l),str(s) {}
    const char* what(){ 
        return str;
    }       
};

当我使用

抛出myex时
throw myexception<int>(0,cont,"Invalid dereferencing: The iterator index is out of range.");, 

我得到一个错误

error: no matching function for call to ‘std::out_of_range::out_of_range()’.
Any help is appreciated.`.

当我取消注释的行,并删除另一个构造函数,然后它工作正常

用户定义的异常的构造函数试图调用out_of_range类的默认构造函数…除非它不存在!

关于注释的构造函数:

myex(const char* err): out_of_range(err) {}
                     //^^^^^^^^^^^^^^^^^ this calls the constructor of 
                     // out_of_range with the parameter err.

为了修复当前的构造函数,应该添加对out_of_range的构造函数的显式调用(该构造函数接受const string&):

myex(li<int> *l,const char* s) : out_of_range(s), li(l),str(s) {}