I was going to write a long post about how to handle exceptions. But, as I was writing it, I was bored…and I realized if writing it was boring me, reading it would likely put you to sleep.
So, instead, I have distilled what I was going to say into a couple of quick bullet points.
- When you have a block of code that can throw different types of exceptions and you are going to handle all of them the same way, just catch the generic exception and handle it once so you don’t violate the DRY (don’t repeat yourself) principle.
- Alternatively, if there are multiple exceptions thrown and you need to handle one of them differently, make sure to break it out.
- Take care in how you handle exceptions.
- Sometimes it is safe to simply log the exception and move on.
- Sometimes it is better to pass the exception up to the calling method, because it will better be able to determine what should be done.
- Sometimes it is safe to return a default (empty) object, and sometimes it is better to return a null.
- Finally, I would suggest that you never swallow an exception. Swallowing an exception is when you have a try/catch block, and then do nothing in the catch block. This will just make your life more difficult in the long run.
I hope this list is helpful, and the post wasn’t too boring! If you have any other tips you would like to share, please feel free to leave them in the comments section!