tags:

views:

30

answers:

2

I'm working on an object that at some point instantiates another object. That inner object might throw an exception. I could just let that exception bubble up to whatever code is handling the parent object, which is what I want to do, following the philosophy of KISS. Or, I could do some exception handling within the parent object, and perhaps give a more meaningful exception to the 'client' code. Is there a general rule to follow, or do I decide what to do on a case-by-case basis?

With the child object, I took the time to write error codes, so at some point in the future I could give the end-user a more meaningful error message. If the parent object and the child object have their own set of error codes, how do I handle that? It seems I would write an exception handler that looks at the error code and its originating class, right?

+1  A: 

If the "outer" object cannot handle the exceptions thrown by the "inner" object then it must not try to. At best it can catch a few of the more common ones and rethrow with slightly more information attached.

Ignacio Vazquez-Abrams
So I should try to do some, but not too much?
Correct. Absorbing and reinterpreting every single exception is pointless busywork.
Ignacio Vazquez-Abrams
So the, do you have to re-throw caught exceptions that you can't handle? If not, how do you sometimes catch exceptions, only when you can handle them? If so, what's the code for this? `catch( exception $e ) { if ( $e->getCode() == 15 ) { ... } else { throw $e; }` ?
You can use a more specific type than Exception in `catch ()`; uncaught exceptions will float up the call stack.
Ignacio Vazquez-Abrams
I think I'm starting to see. You'd want the inner object to throw different exception types -- extensions of the exception class -- and the outer class catches types, rather than having the outer object catch a generic exception, testing it, then passing it.
+1  A: 

Assuming the outer object could not handle the Exception, I would only catch and rethrow it as a different Exception if there was a good reason to hide the inner object. You don't want all of your code to depend on the internals of something that doesn't need to be exposed.

Other than that, if the outer object doesn't know what to do or has nothing to add, it shouldn't really touch the exception.

konforce