单个“抛出”是什么?声明呢? [英] What does a single "throw;" statement do?
问题描述
这些天,我一直在阅读很多 C ++ FAQ ,特别是< a href =http://www.parashift.com/c++-faq-lite/exceptions.html =noreferrer>此页面。
阅读本节我发现一个技巧,作者称之为异常调度程序,允许某人将其所有的异常处理组合在一个方便的功能中:
void handleException()
{
try {
throw; //?
}
catch(MyException& e){
//...code处理MyException ...
}
catch(YourException& e){
//...code来处理YourException ...
}
}
void f()
{
try {
// ...可能会抛出...
}
catch(...){
handleException();
}
}
令人困扰的是单个 throw;
语句:如果你考虑给定的例子,那么确定,它是显而易见的:它重新抛出首先在 f()
并再次处理它。
但是如果我直接调用 handleException()
从 catch()
子句执行它?有没有指定的行为?
除了奖励积分,还有其他奇怪(可能不是好的话)使用 throw
你知道吗?
谢谢。
如果你自己做一个 throw;
,那么它不会被重新抛出,而程序会突然结束。 (更具体地说, terminate()
被调用。)
注意throw;是重新抛出当前异常的唯一安全方式 - 它不等于
catch(exception const& e){throw e; }
These days, I have been reading a lot the C++ F.A.Q and especially this page.
Reading through the section I discovered a "technique" that the author calls "exception dispatcher" that allows someone to group all his exception handling in one handy function:
void handleException()
{
try {
throw; // ?!
}
catch (MyException& e) {
//...code to handle MyException...
}
catch (YourException& e) {
//...code to handle YourException...
}
}
void f()
{
try {
//...something that might throw...
}
catch (...) {
handleException();
}
}
What bothers me is the single throw;
statement: if you consider the given example then sure, it is obvious what it does: it rethrows the exception first caught in f()
and deals with it again.
But what if I call handleException()
on its own, directly, without doing it from a catch()
clause ? Is there any specified behavior ?
Additionally for bonus points, is there any other "weird" (probably not the good word) use of throw
that you know of ?
Thank you.
If you do a throw;
on its own, and there isn't a current exception for it to rethrow, then the program ends abruptly. (More specifically, terminate()
is called.)
Note that throw; is the only safe way to re-throw the current exception - it's not equivalent to
catch (exception const & e) { throw e; }
这篇关于单个“抛出”是什么?声明呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!