How to disable C++ exception handling using macros?

Warning! Some information on this page is older than 6 years now. I keep it for reference, but it probably doesn't reflect my current knowledge and beliefs.

Thu
28
Jul 2016

Some time ago my colleague showed me a clever way to disable exception handling in C++ using a set of preprocessor macros:

#define throw
#define try          if(true)
#define catch(...)   if(false)

Please note that:

So following code that uses exception:

try
{
    // Do something
    if(somethingFailed)
        throw std::exception("Message.");
}
catch(const std::exception& e)
{
    // Handle the exception.
}

Will resolve after defining these three macros to following:

if(true)
{
    // Do something
    if(somethingFailed)
        std::exception("Message.");
}
if(false)
{
    // Handle the exception.
}

Of course it's not a solution to any real problem, unless you just want your try...catch blocks to stop working. Disabling exception handling for real (and associated performance penalty, as well as binary code size overhead) is the matter of compiler options. And of course this trick makes errors not handled properly, so when an exception would be thrown, the program will just continue and something bad will happen instead.

But I think the trick is interesting anyway, because it shows how powerful C++ is (it empowers you to do stupid things :)

Comments | #c++ Share

Comments

[Download] [Dropbox] [pub] [Mirror] [Privacy policy]
Copyright © 2004-2025