【发布时间】:2010-12-09 00:17:56
【问题描述】:
我一直在尝试为我正在开发的 C++ 库创建一些自定义异常类。如果由于某种原因在测试异常时未在正确的位置捕获,这些自定义异常会捕获调试所需的额外信息,例如文件、行号等。然而,大多数人似乎建议从 STL 中的 std::exception 类继承,我同意这一点,但我想知道使用多重继承从 derived std::exception classes 中的每一个继承可能会更好(例如 std: :runtime_error) 和自定义异常类,如下代码所示?
另一件事,异常类中的复制构造函数和赋值运算符如何处理?他们应该被禁用吗?
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();
};
【问题讨论】:
-
你会从中得到什么?为什么不使用单继承?为什么需要自定义 both Exception 和 RuntimeError 异常?
-
我想使用自定义 Exception 类中的功能并通过从各种派生的 std::exception 类继承来维护 STL 异常层次结构。这样可以捕获:try{ throw RunTimeException(...); }catch(std::runtime_error &e){ ... }catch(std::exception &e){...} 也会捕获我的自定义类。但这可能是浪费时间。我也可以尝试{ throw RunTimeException(...); }catch(std::exception &e){...} 但它可能会使识别异常变得更加困难。不知道自定义异常类时的典型做法是什么?
-
我会说只是从 std::runtime_error (或 std::exception)继承。如果你想要一个特定的治疗,你毕竟可以有多个捕获。
-
as @fmuecke points out creating a custom exception class that has the features you describe (adding arbitrary data to the exception) is difficult to get correct(尤其是在 C++ 中)。更容易使用像
boost::exception这样的代码,它经过了广泛的同行评审和实战测试。
标签: c++ stl exception multiple-inheritance