C++: How to catch exceptions thrown from constructors? -
i have class, call a, constructor takes input arguments, , may throw exception if incompatible constructing object. in main code, construct object of type a follows:
a my_obj(arg1,arg2,arg3); and use it. if constructor fails , throws exception, execution of program terminated after printing out 'unhandled exception' message.
i, however, give user more information in case , tell him/her why exception has been thrown. so, need way catch exception.
to end, 1 possibility enclose whole code, starting declaration of my_obj till end of program in try block , catch exception afterwards:
try { my_obj(arg1, arg2, arg3); // ... // 100 other lines of code being executed if my_obj created } catch (std::exception& e) { // print user-friendly error message , exit } but looks me bit of 'overkill'. since no other exceptions thrown in remaining 100 lines. there other nicer way accomplish this?
you can abstract object construction function catches exception:
template<typename... args> make_a(args&&... args) { try { return a(std::forward(args)...); } catch (std::exception& e) { // print user-friendly error message , exit ... std::exit(exit_failure); } } // ... in actual code: my_obj = make_a(arg1, arg2, arg3); the above makes use of fact program exiting if construction fails. if requirement continue running, function return std::optional<a> (or boost equivalent if don't have access c++17.)
Comments
Post a Comment