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 t
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.
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.
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
.