繁体   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