Should I declare unchecked exceptions in the throws specification?

mafu picture mafu · Jan 1, 2014 · Viewed 13.5k times · Source

I'm aware checked exceptions have to be handled or specified, but unchecked exceptions are optional.

If for some reason I can reasonably expect an unchecked exception to occur in a method, should I add it to the throws specification? Or should I keep the specification as short as possible?

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Jan 1, 2014

If for some reason I can reasonably expect an unchecked exception to occur in a method, should I add it to the throws specification?

Since unchecked exceptions indicate programming errors, declaring them in the throws clause should be avoided. Generally, catching these exceptions should not be attempted, except for the highest level of your program. There are a few exceptions (pun intended) to this rule - for example, in production code you should be catching NumberFormatException.

Note: Sometimes, authors of frameworks make their base exception inherit RuntimeException (e.g. HibernateException). Exceptions like that should be caught as well.