• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Should I log an exception before throwing it to the caller?

 
raminaa niilian
Ranch Hand
Posts: 551
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

Thank you.
 
Akhilesh Trivedi
Ranch Hand
Posts: 1599
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
raminaa niilian wrote:My question is whether I should log the original exceptions in my code or let the caller to take care of logging?


What are you using logging for?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15206
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it is more useful to log the exception at the place where you are catching and handling it, not at the place where you are throwing it. In other words, let the caller take care of it.
 
Winston Gutkowski
Bartender
Pie
Posts: 10099
56
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Winston
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic