【发布时间】:2011-01-18 07:45:37
【问题描述】:
这是设置。
我有一个调用多个函数的 C++ 程序,所有这些函数都可能引发相同的异常集,并且我希望每个函数中的异常具有相同的行为 (例如,打印错误消息并将所有数据重置为异常 A 的默认值;只需打印异常 B;干净地关闭所有其他异常)。
似乎我应该能够设置 catch 行为来调用一个简单地重新抛出错误并执行捕获的私有函数,如下所示:
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
}
}
现在,如果在异常类之外调用“handle”会发生什么。 我知道这永远不会发生,但我想知道 C++ 标准是否未定义该行为。
【问题讨论】:
-
它被终止了,但是你想让我做什么?,给你一个编译器来执行这个程序,这样你就可以验证结果了。
-
编译器所做的就是编译它。它会编译,因为句柄的 定义 并没有警告用户它肯定需要加载的异常。编译器不能告诉你关于未定义行为的有用信息,尤其是像这样直到运行时才会被拾取的东西。
标签: c++ exception refactoring