在到达main()函数之前,通过所有嵌套函数重新抛出异常是一个好习惯吗?

时间:2017-04-17 14:51:18

标签: c++

就像我的问题主题一样;

在到达main()函数之前,通过所有嵌套函数重新抛出异常是一个好习惯吗?

让我们说,在我的应用程序中出现单个运行时错误(用户错误或其他任何错误)时,我想要杀死整个程序。执行以下操作是一种很好的做法:

#include <stdexcept>
#include <iostream>

using namespace std;

void func_1(void) {
    cout << "I am in func_1()" << endl;
    cout << "- Throwing exception" << endl;
    cout << endl;
    throw std::runtime_error("ERROR !!!");
}

void func_2(void) {
    try {
        cout << "I am in func_2()" << endl;
        cout << "- Trying func_1()..." << endl;
        cout << endl;
        func_1();
    }
    catch (std::runtime_error & error){
        cout << "I am in func_2()" << endl;
        cout << "- Re-throwing exception." << endl;
        cout << endl;
        throw error;
    }
}

void func_3(void) {
    try {
        cout << "I am in func_3()" << endl;
        cout << "- Trying func_2()..." << endl;
        cout << endl;
        func_2();
    }
    catch (std::runtime_error & error) {
        cout << "I am in func_3()" << endl;
        cout << "- Re-throwing exception." << endl;
        cout << endl;
        throw error;
    }
}

int main() {
    try {
        cout << "I am in main()" << endl;
        cout << "- Trying func_3()..." << endl;
        cout << endl;
        func_3();
    }
    catch (std::runtime_error error) {
        cout << "I am in main()" << endl;
        cout << "- Catching func_3() exception..." << endl;
        cout << endl;
    }

    // Exit:
    getchar();
}

上面的代码是我exit()的替代方案。但说实话,代码管理是可怕的。 因此是一种好的或坏的做法

此外,我不确定性能开销...我知道我刚才说我想在出现任何错误的情况下从我的程序中执行安全退出,因此性能 不是问题。

但是如果在某些时候我会改变主意并编写能够从错误中恢复的代码呢?

让我们说n-functions必须re-throw我的例外才能catch'ed并处理? 我需要什么样的性能开销

1 个答案:

答案 0 :(得分:1)

我不这么认为。当你的程序变大时,你将不得不在main中处理多个异常抛出,完全脱离其原始上下文。

我尝试尽可能地保持所有内容,并在特定的上下文中。例如,如果我有一些处理打开文件的函数,这些函数可能会抛出异常直到open_file调用的第一个调用者。此时,我要么通知用户该文件处于不可访问/故障/无论如何。

在我的主要功能中,我有catch(...)但仅用于记录目的。记录任何无法处理的异常,并且程序存在终端错误。

相关问题