请解释 Java 中的 RuntimeException 以及应该在哪里使用它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3540613/
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-10-30 02:18:23  来源:igfitidea点击:

Please explain RuntimeException in Java and where it should be used

javaexceptionruntimeexception

提问by euphoria83

I am following this great discussion at SO, titled: The case against checked exceptions, but I am unable to follow where exactly RuntimeException should be used and how it is different from normal Exceptions and its subclasses. Googling gave me a complex answer, that is, it should be used to deal with programming logic errors and should be thrown when no Exception should normally occur, such as in the default block of switch-case construct.

我正在关注 SO 上的这个伟大的讨论,标题为:The case against checked exceptions,但我无法理解 RuntimeException 应该在哪里使用以及它与普通异常及其子类有何不同。谷歌给了我一个复杂的答案,那就是它应该用于处理编程逻辑错误,应该在正常情况下不应该发生异常时抛出,例如在switch-case构造的默认块中。

Can you please explain RuntimeException in greater detail here. Thanks.

你能在这里更详细地解释一下 RuntimeException 吗?谢谢。

回答by Michael Borgwardt

I am unable to follow where exactly RuntimeException should be used

我无法理解应该在哪里使用 RuntimeException

That's probably because you are looking at an argument, i.e. people are disagreeing about exactly this point.

那可能是因为您正在查看一个论点,即人们对这一点持不同意见。

and how it is different from normal Exceptions and its subclasses.

以及它与普通异常及其子类的不同之处。

Very simple: All subclasses of Exception(except for RuntimeExceptionand its subclasses) are checkedi.e. the compiler will reject the code unelss you catch or declare them in the method signature. However, subclasses of RuntimeExceptionare unchecked.

很简单:所有的子类Exception(除了RuntimeException和它的子类)的检查,即编译器unelss你赶上将拒绝代码或方法签名中声明它们。然而,子类RuntimeException未经检查

Googling gave me a complex answer, that is, it should be used to deal with programming logic errors and should be thrown when no Exception should normally occur, such as in the default block of switch-case construct.

谷歌给了我一个复杂的答案,那就是它应该用于处理编程逻辑错误,应该在正常情况下不应该发生异常时抛出,例如在switch-case构造的默认块中。

This is the conventional wisdom, which says that for everything that a program can usefully deal with, you should use checked exceptions because then the compiler will forceyou to deal with them. Conversely, programs can typically not deal usefully with programmer errors, thus they don't have to be checked. This is how the Java Standard API uses RuntimeException.

这是传统观点,即对于程序可以有效处理的所有内容,您应该使用已检查的异常,因为这样编译器会强迫您处理它们。相反,程序通常不能有效地处理程序员错误,因此不必检查它们。这就是 Java 标准 API 使用的方式RuntimeException

The discussion you linked to is sparked by the view of some people (this includes me) who think that checked exceptions lead to bad code and should therefore not be used. Since you can't disable exception checking in the compiler, the only way to do this is to use onlyRuntimeExceptionand its subclasses.

您链接到的讨论是由某些人(包括我)的观点引发的,他们认为检查异常会导致错误代码,因此不应使用。由于您无法在编译器中禁用异常检查,因此唯一的方法是使用onlyRuntimeException及其子类。

One observation that IMO supports this view is that the conventional wisdom of "use unchecked exceptions only for programmer error" is in fact mainly a rationalization of backwards-reasoning: there is no code safety reason why the compiler should not force you to deal with programmer errors. However, something like NullPointerExceptionand ArrayIndexOutOfBoundsExceptioncan crop up almost anywhere, and if those were checked, nobody would ever want to program in Java. Thus, the language designers had to make a, huh, exception for those, and make them unchecked. To explain this, they came up with the "unchecked exceptions are for programmer errors" story.

IMO 支持这一观点的一个观察是,“仅对程序员错误使用未经检查的异常”的传统智慧实际上主要是向后推理的合理化:没有代码安全理由为什么编译器不应该强迫您处理程序员错误。然而,像NullPointerExceptionand 之类的东西ArrayIndexOutOfBoundsException几乎可以在任何地方出现,如果这些都被选中,那么没有人会想用 Java 编程。因此,语言设计者不得不为这些设置一个,嗯,例外,并使它们不受检查。为了解释这一点,他们提出了“未经检查的异常是针对程序员错误”的故事。

回答by polygenelubricants

Quotes from Effective Java 2nd Edition, Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors

引自Effective Java 2nd Edition,Item 58:对可恢复条件使用检查异常,对编程错误使用运行时异常

The Java programming language provides three kinds of throwables: checked exceptions, runtime exceptions, and errors. There is some confusion among programmers as to when it is appropriate to use each kind of throwable. While the decision is not always clear-cut, there are some general rules that provide strong guidance.

The cardinal rule in deciding whether to use checked exception or an unchecked one is this:

  • Use checked exceptions for conditions from which the caller can reasonably be expected to recover. By throwing a checked exception, you force the caller to handle the exception in a catchclause or to propagate it outward. Each checked exception that a method is declared to throw is therefore a potent indication to the API user that associated condition is a possible outcome of invoking the method.
  • Use runtime exceptions to indicate programming errors. The great majority of runtime exceptions indicate precondition violations. A precondition violation is simply a failure by the clientof an API to adhere to the contract specified by the API specification.

Java 编程语言提供了三种可抛出对象:已检查异常运行时异常错误。程序员之间对于何时使用每种 throwable 是合适的存在一些混淆。虽然决定并不总是明确的,但有一些通用规则可以提供强有力的指导。

决定是使用受检异常还是未受检异常的主要规则是:

  • 对于可以合理地期望调用者从中恢复的条件,请使用已检查的异常。通过抛出已检查的异常,您可以强制调用者在catch子句中处理异常或将其向外传播。因此,方法声明要抛出的每个已检查异常都是对 API 用户的有力指示,即关联条件是调用该方法的可能结果。
  • 使用运行时异常来指示编程错误。绝大多数运行时异常都表明违反了前提条件。前提条件违规只是API的客户端未能遵守 API 规范指定的合同。

Here's an example:

下面是一个例子:

  • When trying to read a file of arbitrary name, the file may not exists. It's not strictly a programming error when a file does not exist (e.g. perhaps it did before but was then accidentally deleted). Clients may want to recover from this. Thus, FileNotFoundExceptionis a checked exception.
  • If you give a nullstring as a filename, then NullPointerException(or perhaps an IllegalArgumentException-- another contentious debate) should be thrown. Client of the API is supposed to provide a valid string value; nullisn't. As far as the API is concerned, this is a programmer error, which was easily preventable. Both of these exceptions are runtime exceptions.
  • 尝试读取任意名称的文件时,该文件可能不存在。当文件不存在时,严格来说这不是编程错误(例如,可能之前存在但随后被意外删除)。客户可能希望从中恢复。因此,FileNotFoundException是一个受检异常。
  • 如果你给一个null字符串作为文件名,那么NullPointerException(或者可能是IllegalArgumentException另一个有争议的辩论)应该被抛出。API 的客户端应该提供一个有效的字符串值;null不是。就 API 而言,这是一个程序员错误,很容易预防。这两个异常都是运行时异常。

Item 59: Avoid unnecessary use of checked exceptionsalso provides additional guidance:

第 59 条:避免不必要地使用受检异常也提供了额外的指导:

Checked exceptions are a wonderful feature of the Java programming language. Unlike return codes, they forcethe programmer to deal with exceptional conditions, greatly enhancing reliability. That said, overuse of checked exceptions can make an API far less pleasant to use. If a method throws one or more checked exceptions, the code that invokes the method must handle the exceptions in one or more catchblocks, or it must declare that it throwsthe exceptions and let them propagate outward. Either way, it places a nontrivial burden on the programmer.

The burden is justified if:

  • the exceptional condition cannot be prevented by proper use of the API, and
  • the programmer using the API can take some useful action once confronted with the exception.

Unless both of these conditions hold, an unchecked exception is more appropriate.

受检异常是 Java 编程语言的一个很棒的特性。与返回码不同,它们强制程序员处理异常情况,大大提高了可靠性。也就是说,过度使用受检异常会使 API 使用起来不那么愉快。如果一个方法抛出一个或多个检查异常,调用该方法的代码必须在一个或多个catch块中处理异常,或者必须声明它throws是异常并让它们向外传播。无论哪种方式,它都给程序员带来了不小的负担。

在以下情况下,负担是合理的:

  • 不能通过正确使用 API 来防止异常情况,以及
  • 一旦遇到异常,使用 API 的程序员可以采取一些有用的措施。

除非这两个条件都成立,否则未经检查的异常更合适。

So here's a short summary of the recommendation from Effective Java 2nd Edition:

因此,这里是Effective Java 2nd Edition建议的简短摘要:

  • Preventable exceptions that happen due to API user errors should be unchecked.
  • Exceptions that can't be handled reasonably should also be unchecked.
  • Otherwise, the exception should be checked.
  • 取消选中因 API 用户错误而发生的可预防异常。
  • 不能合理处理的异常也应该取消检查
  • 否则,应检查异常。

See also

也可以看看

  • Effective Java 2nd Edition
    • Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors
    • Item 59: Avoid unnecessary use of checked exceptions
    • Item 60: Favor the use of standard exceptions
    • Item 61: Throw exceptions appropriate to the abstraction
    • Item 62: Document all exceptions thrown by each method
  • 有效的 Java 第二版
    • 第 58 条:对可恢复条件使用检查异常,对编程错误使用运行时异常
    • 第 59 条:避免不必要地使用受检异常
    • 第 60 条:赞成使用标准例外
    • 第 61 条:抛出适合抽象的异常
    • 第 62 条:记录每个方法抛出的所有异常


Technical definition

技术定义

An unchecked exceptionis defined as RuntimeExceptionand its subclasses, and Errorand its subclasses. They do not have to be declared in a method's throwsclause.

一个未经检查的异常被定义为RuntimeException和它的子类,并Error和它的子类。它们不必在方法的throws子句中声明。

References

参考

Related questions

相关问题