简体   繁体   English

如何将几个函数调用中的异常一直抛回到main?

[英]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()

Live Example 实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有没有办法让 OpenCL C++ 绑定为所有错误抛出异常? - Is there a way to enable OpenCL C++ bindings to throw exceptions for all errors? 在所有嵌套函数中重新引发异常,直到到达main()函数,这是一种好习惯吗? - Is it a good practice to re-throw exceptions through all the nested functions until the main() function is reached? 在类中引发异常的最佳方法是什么? - What is the best way to throw exceptions in classes? 如何记录函数可能抛出的所有异常? - How to document all exceptions a function might throw? 有没有办法内联一些函数的选择性调用而不是所有函数? - is there any way to inline just some selective calls to a function not all of them? C++ 中定义异常 class 并抛出异常的标准方法 - A standard way in C++ to define an exception class and to throw exceptions 有没有更简单的方法来“漏斗”函数调用? - Is there a simpler way to "funnel" function calls? 处理多个地方的整个异常层次结构的好方法 - Good way to handle a whole hierarchy of exceptions on several places 用主文件中的类初始化 function 的方法是什么? - What is the way to initialize a function with classes in the main file? 所有的OpenCV函数都抛出异常吗? - Does all OpenCV functions throw exceptions?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM