Should I declare unchecked exceptions in the throws specification?

14,590

Solution 1

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.

Solution 2

That is a design decision. Normally you wouldn't do that. But if you think it is crucial for the user of your code to catch an Exception, then it is a way to hint him doing that. Another way would be to just add it to the documentation, and explain why it is important to catch the Exception.

Solution 3

explicitly declaring in throws-clause is not necessary since it is about runtime exceptions, but you should document it in javadoc so users can see under which circumstances this exception might occur and what does it mean.

Share:
14,590
mafu
Author by

mafu

Updated on June 11, 2022

Comments

  • mafu
    mafu almost 2 years

    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?