gnillorted
gnillorted

Reputation: 31

Will turning off exceptions in C++ lead to undefined behavior according to the current standard?

I often hear the C++ exception system can be disabled as you should not pay for what you do not use. If I choose to compile my C++ program without exceptions will it result in undefined behavior?

Upvotes: 3

Views: 617

Answers (2)

Matthieu M.
Matthieu M.

Reputation: 299880

To add to Howard's answer.

The general issue is that code written with exceptions in mind could suddenly become bug-riddled if you turn them off.

A simple call to new for example, is supposed to throw the std::bad_alloc exception if the memory request cannot be honored. In case you turn off exceptions it'll return 0 instead: are you sure that all calls to new check that the return is not 0 ? Even those in the standard library or 3rd party libraries ?

CLang recently introduced a diagnosis that prevents compilation if throw or try are used when compiling with exceptions disabled, because it means that the code has not been properly prepared, but I am unsure wrt the other compilers, so watch out.

Upvotes: 3

Howard Hinnant
Howard Hinnant

Reputation: 218770

The current (and future) C++ standard has no notion of turning off exceptions. So technically yes, doing so leads to undefined behavior, if you ask the language lawyers. Realistically implementations try to define reasonable behavior for this popular extension. Consult your documentation.

Upvotes: 10

Related Questions