0

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

user386436
  • 45
  • 5
  • I don't think so, at least not without some sort of code generation. But it's hard to prove a negative (especially with C++) so i'll just comment. :> IIRC, it's each method's responsibility to ensure the class's contracts are met. – Cogwheel Jul 09 '10 at 02:29
  • You might want to read the responses to _"Why should I not wrap every block in a try-catch"_ (http://stackoverflow.com/questions/2737328/why-should-i-not-wrap-every-block-in-try-catch/). There are a lot of different ways to handle exceptions in C++. – D.Shawley Jul 09 '10 at 10:47

2 Answers2

3

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
  • 84,970
  • 20
  • 145
  • 172
  • 1
    +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 Jul 09 '10 at 02:53
0

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
  • 13,915
  • 5
  • 45
  • 60