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:
throw
is a macro without arguments that resolves to just nothing, so the expression following it will become a standalone expression with its result discarded.try
is a macro without arguments that resolves to an "if" statement, that will smoothly merge with the following { } braces.catch
is also a macro that resolves to "if" statement, but it takes variable number or arguments and doesn't use them in its definition.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 :)