这是设置。
我有一个调用多个函数的 C++ 程序,所有这些函数都可能抛出相同的异常集,并且我希望每个函数中的异常具有相同的行为 (例如,对于异常 A,打印错误消息并将所有数据重置为默认值;对于异常 B,只需打印;对于所有其他异常,则完全关闭)。
似乎我应该能够设置捕获行为来调用一个私有(private)函数,它只是重新抛出错误并执行捕获,如下所示:
void aFunction()
{
try{ /* do some stuff that might throw */ }
catch(...){handle();}
}
void bFunction()
{
try{ /* do some stuff that might throw */ }
catch(...){handle();}
}
void handle()
{
try{throw;}
catch(anException)
{
// common code for both aFunction and bFunction
// involving the exception they threw
}
catch(anotherException)
{
// common code for both aFunction and bFunction
// involving the exception they threw
}
catch(...)
{
// common code for both aFunction and bFunction
// involving the exception they threw
}
}
现在,如果在异常类之外调用“句柄”会发生什么。 我知道这永远不应该发生,但我想知道 C++ 标准是否未定义这种行为。
最佳答案
如果在异常上下文之外调用handle()
,您将throw
而不会处理异常。在这种情况下,标准(参见第 15.5.1 节)规定
If no exception is presently being handled, executing a
throw-expression
with no operand callsterminate()
.
因此您的应用程序将终止。这可能不是您想要的。
关于c++ - 如果我使用 "throw;"无异常抛出会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2288692/