簡體   English   中英

構造函數C ++中的異常

[英]Exceptions in the constructor c++

所以我有一個問題:

class Exception{
    private : string message;
    public : 
    Exception();
    Exception(string str);
    string what();

};
class Something{
public : Something(int m) throw(Exception);
....}

並在cpp文件中:

Exception::Exception()
    {
        message="cant divide by 0";
    }
    Exception::Exception(string str)
    {
        message = str;
    }
    Exception:string what()
    {
        return message;
    }

然后我試圖在一些構造函數中使用它

Something::Something(int m) throw(Exception)
    {
        if (m==0) 
        {
            throw Exception();
        }
     };

並在主要

...
catch(Exception obj){
    cout<<obj.what();

}

並且它顯示“ Exception”沒有命名類型並且未聲明“ obj”,我想知道為什么。

Exception類可能不完整。

在我看來,Exception :: what()的定義不正確。

嘗試...

string Exception::what()
{
    return message;
}

另外,正如其他人提到的那樣,在c ++中,您不必定義函數在Java中的拋出方式。 查看此問題以獲取更多詳細信息...

在函數簽名中拋出關鍵字

Something::Something(int m)
{
    if (m==0) 
    {
        throw Exception();
    }
};

通常,除非它是原始類型,否則我通常會捕獲對拋出的異常的引用。 這樣可以避免復制異常。

嘗試...

...
catch(Exception& obj) {
    cout << obj.what();
}

暫無
暫無

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

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