Wil*_*mKF 29 c++ exception ellipsis throw
如果在我的代码中我有以下代码段:
try {
doSomething();
} catch (...) {
doSomethingElse();
throw;
}
Run Code Online (Sandbox Code Playgroud)
抛出会重新抛出默认省略号处理程序捕获的特定异常吗?
GMa*_*ckG 38
是.该异常处于活动状态,直到它被捕获,并且变为非活动状态.但它一直存在,直到处理程序的范围结束.从标准,强调我的:
§15.1/ 4:抛出的异常临时副本的内存以未指定的方式分配,除了3.7.4.1中所述.只要存在针对该异常执行的处理程序,临时就会持续存在.
那是:
catch(...)
{ // <--
/* ... */
} // <--
Run Code Online (Sandbox Code Playgroud)
在这些箭头之间,您可以重新抛出异常.只有当处理程序范围结束时,异常才会停止存在.
实际上,在§15.1/ 6中,给出的示例与您的代码几乎相同:
try {
// ...
}
catch (...) { // catch all exceptions
// respond (partially) to exception <-- ! :D
throw; //pass the exception to some
// other handler
}
Run Code Online (Sandbox Code Playgroud)
请记住,如果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
}
Run Code Online (Sandbox Code Playgroud)
当然,如果没有投掷,throw;将会到达,你将按预期抛出你捕获的异常.
| 归档时间: |
|
| 查看次数: |
12826 次 |
| 最近记录: |