Check if Exceptions are Enabled using C++

Check if Exceptions are Enabled using C++

C++ applications often rely on exception handling for error reporting and recovery. However, some environments disable exceptions to reduce binary size or improve performance - embedded systems being a common example. In such cases, it may be useful for a program to detect whether exception support is active. This enables developers to switch to alternate error-handling paths. This tutorial explains how to check if exceptions are enabled using C++.

We can detect exceptions using compiler-defined macros. Most compilers expose one of the following macros:

  • __cpp_exceptions - a standard feature macro defined when C++ exceptions are enabled. Supported by GCC and Clang.
  • _CPPUNWIND - defined only by MSVC when exception handling and stack unwinding are available.

Because of this difference, we can implement a small compatibility layer that functions across compilers:

#include <iostream>

#if defined(__cpp_exceptions) || defined(_CPPUNWIND)
#define EXCEPTIONS_ENABLED 1
#else
#define EXCEPTIONS_ENABLED 0
#endif

int main() {
    if (EXCEPTIONS_ENABLED) {
        std::cout << "Exceptions enabled" << std::endl;
    } else {
        std::cout << "Exceptions not enabled" << std::endl;
    }

    return 0;
}

To verify the macro logic, compile the program without exceptions support by passing the appropriate option to the compiler:

g++ -fno-exceptions main.cpp -o test

Run the binary:

./test

The executable will print whether exception support is available. This approach is especially helpful when maintaining code intended to run in both exception-enabled and exception-disabled environments.

Leave a Comment

Cancel reply

Your email address will not be published.