In each of my main functions, I would like to catch certain classes of exceptions and convert them to exit codes.
Is there a more elegant solution to this than starting and ending each main function with macros that will paste the implicit try {} catch
I want?
Can I somehow achieve this with the std::set_terminate
functionality?
Example:
JavaScript
x
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; }
}
Advertisement
Answer
A clean way involves using a translation function with all of your exception boilerplate that returns the exit values for the corresponding exception.
JavaScript
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; }
In your own code, you only concern yourself with wrapping your business logic with a lambda and passed that into the translation function so it can capture and translate for you.
JavaScript
int main() {
return call_and_translate_for_boundary([&]{
//business logic here
});
}