我一直在尝试为正在处理的C++库制作一些自定义异常类。这些自定义异常会捕获调试所需的额外信息,例如文件,行号等,如果由于某种原因而在测试异常时没有找到正确的位置。然而,大多数人似乎建议继承STL中的std :: exception类,我同意这一点,但我想知道使用多继承来继承每个derived std::exception classes(例如std :: runtime_error )和一个自定义异常类,如下面的代码所示?C++中的自定义异常
另一件事,如何才能在异常类中复制构造函数和赋值运算符?他们应该被禁用?
class Exception{
public:
explicit Exception(const char *origin, const char *file,
const int line, const char *reason="",
const int errno=0) throw();
virtual ~Exception() throw();
virtual const char* PrintException(void) throw();
virtual int GetErrno(void);
protected:
std::string m_origin;
std::string m_file;
int m_line;
std::string m_reason;
int m_errno;
};
class RuntimeError: public virtual std::runtime_error, public Exception{
public:
explicit RuntimeError(const char *origin, const char *file,
const int line, const char *reason="",
const int errno=0) throw();
virtual ~RuntimeError() throw();
};
你会从中得到什么?为什么不使用单继承?为什么你需要自定义* Exception和RuntimeError异常? – jalf 2009-10-22 09:40:40
我想使用我自定义的Exception类中的功能,并通过继承各种派生的std :: exception类来维护STL异常层次结构。通过这种方式搭配: 尝试throw RunTimeException(...); (std :: runtime_error&e){ ... } catch(std :: exception&e){...} 也会捕获我的自定义类。 虽然这可能是浪费时间。我也可以只用 尝试throw RunTimeException(...); } catch(std :: exception&e){...} 但它可能会使识别异常更困难。自定义异常类时,我不知道典型的做法是什么? – Tom 2009-10-22 10:16:05
我会说只是从std :: runtime_error(或std :: exception)继承。如果你想要一个特定的治疗,你可以有多个捕获。 – 2009-10-22 18:36:39