繁体   English   中英

捕获自定义异常C ++

[英]Catch custom exception C++

我有一个异常类:

#ifndef OBJECTEXCEPTION_H_
#define OBJECTEXCEPTION_H_

class ObjectException: public std::logic_error
{
public:
    ObjectException (const std::string& raison)
            :std::logic_error(raison){};
};

class Object1Exception: public ObjectException
{
public:
    Object1Exception (const std::string& raison)
    : ObjectException(raison){};
};

#endif 

我有一个抛出此异常的方法:

void Object1::myMethod(int type) {
if (type == 0) {
    throw new Object1Exception(type);
}

...
}

现在,我使用这种方法:

try{
    obj1->myMethod(0);
}
catch(Object1Exception& error){

}

但是我有这个错误

terminate called after throwing an instance of 'tp::Object1Exception*'

我不明白为什么未捕获到异常。

代码throw Object1Exception(type); 没有new ; 您将抛出一个指向异常的指针 ,而不是异常本身。

顺便说一句,正如polkadotcadaver所评论的那样 ,错误消息非常清楚,它告诉您关于抛出某种指针类型throwing an instance of 'tp::Object1Exception*' ...。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM