簡體   English   中英

自定義out_of_range異常

[英]Custom out_of_range exception

我想編寫一個StrExcept異常類,該類通過定義其自己的構造函數和一個向用戶輸出自定義錯誤消息的print()方法,從基本異常類out_of_range繼承。

現在,這是我的代碼:

class StrExcept: public out_of_range
{
string message;

public:


StrExcept():out_of_range("The value entered is out of range"),message("The value entered is out of range"){};

void print(){
    cout << message;
}

};

內部主要方法:

try
{
    string str="My name";
    // the exception will be fired
    str.substr(11,2);
}
// i want to catch it using this custom class
catch (StrExcept &outOfRange )
{
    // i want to print the error message using print method
   outOfRange.print();

}

但是為什么不起作用呢? 和程序崩潰???

僅僅因為您派生自一個類並不意味着已經存在的代碼(例如basic_string::substr的實現)將使用它。 該函數將拋出std::out_of_range catch(const StrExcept&)將僅捕獲類型為StrExceptStrExcept派生的類的異常,而不是拋出該異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM