如果在我的代码中有以下代码段:
try {
doSomething();
} catch (...) {
doSomethingElse();
throw;
}
throw 是否会重新抛出默认省略号处理程序捕获的特定异常?
最佳答案
是的。异常在被捕获之前一直处于事件状态,此时它变为非事件状态。但是它会一直存在到处理程序的范围结束。从标准来看,强调我的:
§15.1/4: The memory for the temporary copy of the exception being thrown is allocated in an unspecified way, except as noted in 3.7.4.1. The temporary persists as long as there is a handler being executed for that exception.
即:
catch(...)
{ // <--
/* ... */
} // <--
在这些箭头之间,您可以重新抛出异常。只有在处理程序范围结束时,异常才会停止存在。
事实上,在 §15.1/6 中给出的示例与您的代码几乎相同:
try {
// ...
}
catch (...) { // catch all exceptions
// respond (partially) to exception <-- ! :D
throw; //pass the exception to some
// other handler
}
请记住,如果您 throw
没有事件异常,则将调用 terminate
。在处理程序中,这对您来说不是这种情况。
如果 doSomethingElse()
抛出并且异常没有相应的处理程序,因为原始异常被认为已处理,新异常将替换它。 (好像它刚刚抛出,开始堆栈展开等)
即:
void doSomethingElse(void)
{
try
{
throw "this is fine";
}
catch(...)
{
// the previous exception dies, back to
// using the original exception
}
try
{
// rethrow the exception that was
// active when doSomethingElse was called
throw;
}
catch (...)
{
throw; // and let it go again
}
throw "this replaces the old exception";
// this new one takes over, begins stack unwinding
// leaves the catch's scope, old exception is done living,
// and now back to normal exception stuff
}
try
{
throw "original exception";
}
catch (...)
{
doSomethingElse();
throw; // this won't actually be reached,
// the new exception has begun propagating
}
当然,如果没有抛出任何异常,throw;
将被触发,您将按预期抛出捕获的异常。
关于c++ - throw 在 catch 省略号 (...) 中是否会重新抛出 C++ 中的原始错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2474429/