一个隐含的try {}抓住了main

PSk*_*cik 8 c++ linux c++11

在我的每个主要函数中,我想捕获某些类别的异常并将它们转换为退出代码.

有没有一个更优雅的解决方案,比使用宏来开始和结束每个主要功能,将粘贴try {} catch我想要的隐含?

我能以某种方式实现这一std::set_terminate功能吗?

例:

int main(){
    try { //<- insert this

    /*
    the business logic goes here
    */

    //-> and insert this
    }
    catch(const Someclass1& e){ return 2; }
    catch(const Someclass2& e){ return 3; }
    //...
    catch(...){ return 1; } 
}
Run Code Online (Sandbox Code Playgroud)

Sno*_*awk 6

一种干净的方法是使用转换函数和所有异常样板,它返回相应异常的退出值.

template <typename Callable>
int call_and_translate_for_boundary(Callable&& func)
try {
    func();
    return 0;
}
catch(const Someclass1& e){ return 2; }
catch(const Someclass2& e){ return 3; }
//...
catch(...){ return 1; } 
Run Code Online (Sandbox Code Playgroud)

在您自己的代码中,您只关心自己用lambda包装业务逻辑并将其传递给翻译函数,以便它可以为您捕获和翻译.

int main() {
    return call_and_translate_for_boundary([&]{
        //business logic here
    });
}
Run Code Online (Sandbox Code Playgroud)