Are C++ programs using exceptions required to have try/catch block in their main function?

Viewed 224

If the exception is thrown by the C++ code but is not caught, it causes SIGABRT. Some systems just print "Abort", some other systems also print the contents of e.what().

The question is: Does the C++ standard say that try/catch block is required in the main function for the program to be considered a well behaved program, or does C++ just silently rely on the system to process this?

2 Answers

As described in C++17 standard draft, in section 18.3.9 [except.handle]:

If no matching handler is found, the function std::terminate() is called; whether or not the stack is unwound before this call to std::terminate() is implementation-defined.

So, the behavior of such program is not considered undefined, since standard defines, that std::terminate will be called.

No, C++ standard doesn't require every exception to be caught. If the exception is not caught, the program terminates, and it is implementation-defined if stack unwinding is happening (it does with all the compilers I know). Further reading: https://en.cppreference.com/w/cpp/language/throw

Related