我应该在throws规范中声明未经检查的异常吗? [英] Should I declare unchecked exceptions in the throws specification?

查看:105
本文介绍了我应该在throws规范中声明未经检查的异常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道必须处理或指定已检查的异常,但是未检查的异常是可选的。

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

如果出于某种原因,我可以合理地期望发生未检查的异常在方法中,应该将其添加到throws规范中吗?还是应该使规范尽可能短?

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?

推荐答案


如果出于某些原因我可以合理地使用期望方法中会发生未经检查的异常,是否应该将它添加到throws规范中?

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

由于未经检查的异常表明 programming错误,应避免在 throws 子句中声明它们。通常,除程序的最高级别外,不应尝试捕获这些异常。该规则有一些例外情况(例如双关语)-例如,在生产代码中,您应该捕获 NumberFormatException

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.

注意:有时,框架的作者会使其基本异常继承 RuntimeException (例如 HibernateException )。这样的异常也应该被捕获。

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

这篇关于我应该在throws规范中声明未经检查的异常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆