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

发布于 2024-09-15 07:03:05 字数 303 浏览 6 评论 0原文

我正在关注 SO 上的这个精彩讨论,标题为: 针对检查异常的案例 ,但是我无法理解 RuntimeException 到底应该在哪里使用以及它与普通异常及其子类有何不同。谷歌搜索给了我一个复杂的答案,即它应该用于处理编程逻辑错误,并且应该在通常不应该发生异常的情况下抛出,例如在 switch-case 构造的默认块中。

您能在这里更详细地解释 RuntimeException 吗?谢谢。

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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

如果没结果 2024-09-22 07:03:06

引自《Effective Java 第二版》,第 58 条:对可恢复条件使用检查异常,对编程错误使用运行时异常

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

决定使用检查异常还是非检查异常的基本规则是:

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

下面是一个示例:

  • 当尝试读取任意名称的文件时,该文件可能不存在。当文件不存在时(例如,可能以前存在但后来被意外删除),严格来说这并不是一个编程错误。客户可能希望从中恢复。因此, FileNotFoundException 是一个已检查的异常。
  • 如果您提供 null 字符串作为文件名,则 NullPointerException (或者可能是 IllegalArgumentException——另一个有争议的争论)应该被抛出。 API 的客户端应该提供有效的字符串值; null 不是。就 API 而言,这是一个程序员错误,很容易预防。这两个异常都是运行时异常。

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

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

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

  • 正确使用 API 无法避免异常情况,
  • 使用 API 的程序员在遇到异常时可以采取一些有用的操作。

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

因此,这里是《Effective Java 第二版》的建议的简短摘要:

  • 取消检查由于 API 用户错误而发生的可预防异常。
  • 无法合理处理的异常也应该取消检查
  • 否则,应该检查异常

另请参阅

  • 《Effective Java 第二版》
    • 第 58 项:针对可恢复条件使用检查异常,针对编程错误使用运行时异常
    • 第 59 项:避免不必要地使用已检查异常
    • 第 60 项:支持使用标准异常
    • 第 61 项:抛出适合抽象的异常
    • 第 62 项:记录每个方法抛出的所有异常

技术定义

未经检查的异常是定义为 RuntimeException 及其子类,以及 Error 及其子类。它们不必在方法的 throws 子句中声明。

参考文献

相关问题

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

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 catch clause 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 client of an API to adhere to the contract specified by the API specification.

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, FileNotFoundException is a checked exception.
  • If you give a null string 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; null isn't. As far as the API is concerned, this is a programmer error, which was easily preventable. Both of these exceptions are runtime exceptions.

Item 59: Avoid unnecessary use of checked exceptions also provides additional guidance:

Checked exceptions are a wonderful feature of the Java programming language. Unlike return codes, they force the 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 catch blocks, or it must declare that it throws the 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.

So here's a short summary of the recommendation from 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.

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

Technical definition

An unchecked exception is defined as RuntimeException and its subclasses, and Error and its subclasses. They do not have to be declared in a method's throws clause.

References

Related questions

鱼忆七猫命九 2024-09-22 07:03:05

我无法准确追踪到哪里
应使用 RuntimeException

这可能是因为您正在查看一个争论,即人们在这一点上存在分歧。


它与正常有何不同
异常及其子类。

非常简单:Exception 的所有子类(除了 RuntimeException 及其子类)都被检查,即编译器将拒绝该代码,除非您捕获或声明它们在方法签名中。但是,RuntimeException 的子类未经检查

谷歌搜索给了我一个复杂的答案,
也就是说,它应该用来处理
有编程逻辑错误和
没有异常时应该抛出
通常应该发生,例如在
switch-case 的默认块
构造。

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

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

IMO 支持这种观点的一个观察是,“仅在程序员错误时使用未检查的异常”的传统智慧实际上主要是向后推理的合理化:没有代码安全原因为什么编译器不应该强迫你与程序员打交道错误。然而,像 NullPointerException 和 ArrayIndexOutOfBoundsException 之类的异常几乎可以在任何地方出现,如果检查了这些异常,就没有人愿意用 Java 进行编程。因此,语言设计者必须为这些例外,并让它们不受检查。为了解释这一点,他们提出了“未经检查的异常是针对程序员错误的”故事。

I am unable to follow where exactly
RuntimeException should be used

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 RuntimeException and its subclasses) are checked i.e. the compiler will reject the code unelss you catch or declare them in the method signature. However, subclasses of RuntimeException are unchecked.

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.

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 force you 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.

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 only RuntimeException and its subclasses.

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 NullPointerException and ArrayIndexOutOfBoundsException can 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文