Java 我应该在 throws 规范中声明未经检查的异常吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20871763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:54:45  来源:igfitidea点击:

Should I declare unchecked exceptions in the throws specification?

javaexceptionthrows

提问by mafu

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?

如果由于某种原因我可以合理地预期方法中会发生未经检查的异常,我是否应该将其添加到 throws 规范中?或者我应该保持规范尽可能短?

回答by Sibbo

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.

这是一个设计决定。通常你不会这样做。但是,如果您认为代码的用户捕获一个 是至关重要的Exception,那么这是暗示他这样做的一种方式。另一种方法是将其添加到文档中,并解释为什么捕获Exception.

回答by Meno Hochschild

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.

没有必要在 throws-clause 中显式声明,因为它是关于运行时异常的,但您应该将其记录在 javadoc 中,以便用户可以看到在什么情况下可能会发生此异常及其含义。

回答by dasblinkenlight

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

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

Since unchecked exceptions indicate programming errors, declaring them in the throwsclause 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.

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

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

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