views:

53

answers:

2

Hi, I am trying to use one exception handler to handle all exceptions raised by a C++ class. is there a simple way, instead of adding the code to every member function?

Thanks

+3  A: 

There's no simple way that you should be doing.

The point of exceptions is that they handle exceptional conditions -- ie: stuff that is unexpected. And that they cause execution to bubble up to code that knows how to handle them. If you have a defined point in your class that should handle all exceptions, either you know they're going to be thrown and want to swallow them (read: you're abusing exceptions) or you don't know they're going to be thrown and just want to swallow them to hide errors (read: you're creating a debugger's nightmare AND abusing exceptions).

If you can't easily handle an exception, just let it be thrown. Don't swallow it, don't pretend it didn't happen.

cHao
+1 Seeing `try/catch` blocks everywhere makes my hair stand on end. If you aren't handling the exception, let it go up the stack until someone handles it.
D.Shawley
A: 

I completely agree with cHao.

If you just want to make sure that some trivial exception doesn't crash your program, then for example if you are writing a GUI application, you could wrap your event loop in a try/catch block, and then depending on the exception, decide to log it, tell the user, ask for permission to send an error report, make the program shut down (nice if you restart it automatically...), etc. (If it got all the way out of your event loop without being caught, you probably want to know about it!)

Ryan Ginstrom