Pupsik
Pupsik

Reputation: 742

Catching exception with unreferenced local variable warning

I've the following code:

try {
    // do some stuff
}
catch(const my_exception_type& e) {
    LOG("Exception %s", e.what());
    throw;
}

The problem is that in debug build the LOG is defined as #define LOG(...) real_logger(...), but in release build is defined as #define LOG(...) \\ do nothing.

Of course when I'm compiling my release code in Visual Studio, I'm getting the warning C4101: 'e' : unreferenced local variable.

What is the best practice to handle exception logging without generation any unnecessary warnings?

P.S
I'm doing nothing with the exception except logging and re-throwing it.

Upvotes: 13

Views: 14040

Answers (2)

Sga
Sga

Reputation: 3658

You can #ifdef each catch line (very invasive) or add just a line in each catch block:

catch(const my_exception_type& e) {
    UNREFERENCED_PARAMETER(e);
    LOG("Exception %s", e.what());
    throw;
}

And the warning is gone. Or, you can #define MY_EXCEPTION_CATCH(...) to define the e parameter only in debug build.

Upvotes: 4

Matthias247
Matthias247

Reputation: 10396

You can mark the object as "used" by casting it to void. It has no influence on the generated machine code, but it will suppress the compiler warning.

try {
    // do some stuff
}
catch(const my_exception_type& e) {
    (void)e;
    LOG("Exception %s", e.what());
    throw;
}

Upvotes: 8

Related Questions