[英]Defining exception classes
我想知道為給定程序定義自己的異常類通常是一種好習慣。 例如,我有一個程序,主要用於讀取/寫入文件以及修改iptables規則。 我也將該程序編寫為自己的基本記錄器類。 為了處理意外的值或錯誤,例如打開文件,我通常使用std::runtime_error
。 我想知道定義自己的異常類是否通常是一個好主意。 例:
void Protocol::set_port(const unsigned long &port) {
if ( (port > 0) && (port < 65535) ) {
port_ = port;
}
else {
throw std::invalid_argument("Invalid port number");
}
}
我不喜歡使用一大堆try and catch塊,因為我發現這是一個不好的丑陋的做法(盡管我可能錯了)。
我想知道為給定程序定義自己的異常類通常是一種好習慣。
是的,通常,異常的類型應描述來源或原因,因此您可以通過模式匹配而不是代碼來處理該特定異常。
我通常使用std :: runtime_error。 我想知道定義自己的異常類是否通常是一個好主意。
是的,通常應遵循以下規則:
顯然,僅使用異常報告異常故障(即,不滿足前提條件,或由於程序錯誤操作之外的原因導致資源不可用)。
如果失敗是邏輯錯誤(調用方試圖在程序域內執行非法操作),則從std::logic_error
派生異常。
如果失敗是由於參數無效而導致的,那么從std::invalid_argument
派生是有意義的。
如果失敗是運行時錯誤(例如文件丟失),則從std::runtime_error
派生。
嵌套異常也很有用,因為您可以同時傳遞異常的摘要和原因,以便以后進行診斷,例如:
struct port_out_of_range : std::invalid_argument
{
port_out_of_range(std::string const& context, unsigned long given)
: std::invalid_argument(context + ": port given: " + std::to_string(given))
{
}
};
void Protocol::set_port(const unsigned long &port)
{
if ( port < 65535 ) {
port_ = port;
}
else {
throw port_out_of_range("Protocol::set_port", port);
}
}
...稍后...
try {
// ... some things ...
foo.set_port(x);
// ... more things ...
}
catch(port_out_of_range& e)
{
// maybe some remedial action possible here
}
catch(std::exception& e)
{
// but not here
log(e);
throw;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.