This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I am writing some code and in my code lot's of exceptions can happen, exceptions like IO and XML parsing exceptions. I am wrapping these exceptions into a domain friendly runtime exception and throw them up to the caller code. My question is whether I should log the original exceptions in my code or let the caller to take care of logging?
raminaa niilian wrote:I am writing some code and in my code lot's of exceptions can happen, exceptions like IO and XML parsing exceptions...
I think it might be worth first looking into why your program can throw so many exceptions, and whether you can do anything to prevent them. There are several defensive programming techniques such as proper parameter (and sometimes return value) checking, not returning nulls, and good documentation that can help to minimise these issues; but at the end of the day, an error is an error, and it may be just as easy to let it be caught where it should be - or indeed not at all.
Another question to ask yourself is: can the program be reasonably expected to recover from the error? In the case of an I/O exception the answer is usually 'no', so it may be just as easy to simply let the program fail; in the case of a parsing error, only you will know. You may also be able to help out users by providing good diagnostic messages, but to do that you generally need to catch the exception as early as possible.
Sorry if it's not specific enough for you, but exception handling is a complex subject, and there is no "right" answer. Personally, I'm a bit skeptical of one-stop "exception handlers", but it may just be because I've never found one that does everything I want.
Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here