我一直在嘗試爲正在處理的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