Should I declare unchecked exceptions in the throws specification?

前端 未结 3 2027
粉色の甜心
粉色の甜心 2021-01-31 09:13

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

3条回答
  •  野性不改
    2021-01-31 09:31

    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.

提交回复
热议问题