简体   繁体   English

C++ catch(std::exception & e) 与 catch(...)

[英]C++ catch(std::exception & e ) vs. catch(...)

I know the difference in handling of both of these catches, but what does it take for the ellipse to catch something the std::exception catch wouldn't catch?我知道处理这两个捕获的区别,但是椭圆捕获 std::exception 捕获不会捕获的东西需要什么?

For example:例如:

try
{
    throw std::runtime("runtime error!");
}
catch(const std::exception& e)
{
    std::cout << "Exception: " << e;
}
catch(...)
{
    std::cout << "How did I get here?";
    throw;
}

I've seen examples of code that use both of these in conjunction, but I've not seen a reason you would do both.我已经看到将这两种方法结合使用的代码示例,但我没有看到您同时使用这两种方法的理由。

catch(const std::exception& e)

Will catch std exceptions only.只会捕获 std 异常。

catch(...)

Will catch everything there after.之后会抓住一切。

You can handle integers and other types ( http://www.cplusplus.com/doc/tutorial/exceptions/ )您可以处理整数和其他类型( http://www.cplusplus.com/doc/tutorial/exceptions/

For example:例如:

catch(int e)

While it's definitely a good idea to do so, you don't have to derive your custom exceptions from std::exception .虽然它绝对是一个好主意,这样做,你就不必从派生自定义异常std::exception C++ allows you to throw practically any object type. C++ 允许您抛出几乎任何对象类型。

So throw 1;所以throw 1; will not be handled by your first handler, for example.例如,不会由您的第一个处理程序处理。 And neither will...而且也不会...

class MyCustomException { // Doesn't derive
 ///
};

... if it was thrown. ...如果它被抛出。

You probably meant:你可能的意思是:

throw std::runtime_error("runtime error!"); // not std::runtime

The std::runtime_error is derived from the std::exception so your first catch block is fired up as it catches exceptions of type std::exception . std::runtime_error派生自std::exception ,因此您的第一个 catch 块在捕获std::exception类型的异常时被触发。 And there you probably meant:你可能的意思是:

std::cout << "Exception: " << e.what(); // not e

If you threw anything else other than the std::run_time or std::exception and its derivatives, the second catch block would be triggered.如果您抛出std::run_timestd::exception及其派生类以外的任何其他内容,则将触发第二个catch块。 Useful reading from the C++ FAQ: What should I throw?来自 C++ FAQ 的有用阅读:我应该抛出什么?

As written, the throw statement throws an object whose type is derived from std::exception , so it's caught by the first catch clause.正如所写, throw语句抛出一个类型派生自std::exception的对象,因此它被第一个catch子句catch If you change the throw to throw 3;如果你把投掷改为throw 3; the exception will be caught by the second catch clause, not the first.异常将被第二个catch子句catch ,而不是第一个。

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

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