[英]Way to throw exceptions out of several function calls all the way back to main?
What is the "right" way to throw exceptions out of several function calls all the way back to main? 将异常从几个函数调用中一直抛回到main的“正确”方法是什么?
What I'm doing now is for example: 我现在正在做的是例如:
void foo() {
...
try {
...
}catch(a1) {
...
throw(a2);
}
...
}
void baz() {
...
try {
foo();
}catch(a2) {
...
throw(a3);
}
...
}
etc 等等
There's got to be a better way to throw consequently and go out of call stack without catching every exception on the way, is it? 必须有一个更好的方法来抛出并退出调用堆栈而不会在途中捕获每个异常,是吗?
Per [except.throw] Per [except.throw]
When an exception is thrown, control is transferred to the nearest handler with a matching type (15.3); 抛出异常时,控制转移到具有匹配类型的最近的处理程序(15.3); “nearest” means the handler for which the compound-statement or ctor-initializer following the try keyword was most recently entered by the thread of control and not yet exited. “nearest”表示最后由控制线程输入并且尚未退出的try关键字后面的复合语句或ctor-initializer的处理程序。
This means that if an exception is thrown and none of the handlers match its type the exception will propagate up until it finds one or none are found. 这意味着如果抛出异常并且没有处理程序与其类型匹配,则异常将向上传播,直到找到一个或没有找到。 You can see this working in this little example 您可以在这个小例子中看到这个
#include <iostream>
#include <exception>
void foo3() { std::exception e; throw(e); }
void foo2() { try { foo3(); } catch (std::bad_exception){} }
void foo() { foo2(); }
int main()
{
try
{
foo();
}
catch (std::exception & e)
{
std::cout << "caught in main()";
}
}
Output: 输出:
caught in main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.