tags:

views:

129

answers:

3

Hi,

I'm trying to write two simple macros for begin and end of functions in order to manage and log all the Exceptions in my program. In other words, I wanna have a try-catch block in all of my functions.

in simple case consider the following macros.

#define __BEGIN_FUNCTION__ try {
#define __END_FUNCTION__ } catch(std::exception e) \
{ log << time << ':' << e << endl; }

but if I put these two macros in beginning and end of a function, the compiler will give the "Not all control paths return a value" error.

any solution?

+5  A: 

Instead of doing this, why not let the exceptions bubble up to the top and handle it in one place?

Only catch exceptions if you can do something about it.

Jeff Foster
+15  A: 

That's a horrible way to handle exceptions. If an exception is thrown, it is because an error occurred. You then have to either handle the error, solving the problem that occurred, or allow it to terminate the program.

Ignoring the exception makes no sense.

At the very least, you should rethrow the exception once it's been logged. Change the END_FUNCTIONmacro to include a throw;. That should also solve the compiler error you're getting.

A final note: your macro names are very badly chosen. Names that either:

  • contain a double underscore or
  • begin with an underscore followed by a capital letter

are reserved for use by the implementation (the compiler and the standard library.

You risk conflicts by using names like those anywhere in your program.

You should also note that catching exceptions should be done by reference (catch (const std::exception& e), and that it won't catch exceptions not derived from std::exception. If you want to catch everything that is thrown, use catch(...).

jalf
+4  A: 

I know you don't want to hear it, but the answer is to only include try/catch blocks when they're appropriate. What you're trying to do here is basically be really, really lazy, in a way which provides almost zero benefit. It's even worse, because you're catching everything as a generic exception, and treating none of your exceptions like they deserve to be treated.

The answer is "Don't do it."

EricBoersma
Eric, why do you think, he doesn't want to hear it. It is never wrong to suggest the best method.
I just assumed he didn't want to hear it because I figured he'd probably already had the thought himself. :)
EricBoersma