在C++中抛出和捕获自定义异常的问题

Neo*_*Man 1 c++ exception try-catch

我创建了Someting类,当它无法实例化时抛出异常SomethingException(SomethingException继承自std :: exception).问题是我无法捕捉SomethingException(我不得不做一个肮脏的技巧来抓住它).

程序中的某个位置执行: 这不起作用,异常未被捕获且程序崩溃.

try{
    Something* s = new Something();
}
catch (SomethingException* e){
    std::cerr<<e.what();
}
Run Code Online (Sandbox Code Playgroud)

相反,这确实有效(捕获异常并显示正确的消息)但我真的有感觉我不应该这样做

try{
    Something* s = new Something();
}
catch (std::exception* e){
    SomethingException* e2 = (SomethingException*) e;
    std::cerr<<e.what();
}
Run Code Online (Sandbox Code Playgroud)

因为指针是铸造的,所以当且仅当抛出一种类型的异常时,我才能使这个工作.我需要捕捉各种类型的那一刻不起作用.

有没有办法以更正确的方式捕获自定义异常?

编辑:

抛出异常如下

//...
throw new SomethingException ("Errormessage"); //Custom exception constructor
//...
Run Code Online (Sandbox Code Playgroud)

Something :: Something()的声明是

Something::Something() throw(...)
Run Code Online (Sandbox Code Playgroud)

使用声明

Something::Something() throw(SomethingException)
//or
Something::Something() throw(SomethingException*)
Run Code Online (Sandbox Code Playgroud)

引发很多警告(警告C4290)

Jon*_*rdy 7

通常,最好按值抛出异常并通过引用捕获它们:

try {

    throw SomethingException();

} catch (const SomethingException& error) {

    std::cerr << error.what() << '\n';

}
Run Code Online (Sandbox Code Playgroud)

catch (SomethingException*)如果要扔掉它,你将只能捕获异常throw new SomethingException().您的问题中没有足够的信息可以告诉,但问题可能在于如何SomethingException从中获取std::exception.验证或更改它以继承,比如说std::runtime_errorstd::logic_error代替.

另外,不要使用throw说明符.只是不要.没有编译器为使用已检查的异常提供任何好处:实际上,除非在不符合说明符的异常情况下失败(抛出),否则不会检查已检查std::bad_exception的异常.这可能是你的代码中发生的事情.

  • @NeonMan:你应该摆脱函数上的`throw(SomethingException)`说明符.实际上没有理由认为用户定义的异常无法正常工作,并且您的帖子中没有足够的信息来说明您的问题所在. (2认同)
  • @NeonMan:我建议*函数声明中没有任何抛出说明符*,是的,在函数体中`throw SomethingException();`. (2认同)

Ric*_*ead 6

对于其他可能遇到问题的问题,从std :: exception派生的自定义异常被抛出但未被捕获,还要检查: - 继承是公共的 - 如果在另一个DLL中声明了异常,则异常类是从DLL导出.奇怪的是,如果不是这样,这不会产生链接错误(在VS2012中),它就不会被捕获.