我想通過定義自己的構造函數和向用戶輸出自定義錯誤消息的print()方法來編寫繼承自基本異常類out_of_range的StrExcept異常類。自定義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();
}
但是,爲什麼不工作???和程序崩潰?
首先,異常被const引用。 – DeiDei