Java 异常和错误的区别

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

Differences between Exception and Error

javaexceptionthrowable

提问by Marco Leung

I'm trying to learn more about basic Java and the different types of Throwables, can someone let me know the differences between Exceptions and Errors?

我正在尝试更多地了解基本的 Java 和不同类型的 Throwables,有人可以让我知道异常和错误之间的区别吗?

采纳答案by Eddie

Errors should not be caught or handled (except in the rarest of cases). Exceptions are the bread and butter of exception handling. The Javadocexplains it well:

不应捕获或处理错误(极少数情况除外)。异常是异常处理的基础。该Javadoc中解释说得好:

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.

Error 是 Throwable 的一个子类,它指示合理的应用程序不应尝试捕获的严重问题。大多数此类错误是异常情况。

Look at a few of the subclasses of Error, taking some of their JavaDoc comments:

看看 的几个子类,看看Error他们的一些 JavaDoc 注释:

  • AnnotationFormatError- Thrown when the annotation parser attempts to read an annotation from a class file and determines that the annotation is malformed.
  • AssertionError- Thrown to indicate that an assertion has failed.
  • LinkageError- Subclasses of LinkageError indicate that a class has some dependency on another class; however, the latter class has incompatibly changed after the compilation of the former class.
  • VirtualMachineError- Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating.
  • AnnotationFormatError- 当注解解析器尝试从类文件中读取注解并确定注解格式错误时抛出。
  • AssertionError- 抛出表示断言失败。
  • LinkageError- LinkageError 的子类表示一个类对另一个类有某种依赖;但是,在编译前一个类后,后一个类发生了不兼容的变化。
  • VirtualMachineError- 抛出表示 Java 虚拟机已损坏或已用完其继续运行所需的资源。

There are really three important subcategories of Throwable:

实际上有以下三个重要的子类别Throwable

  • Error- Something severe enough has gone wrong the most applications should crash rather than try to handle the problem,
  • Unchecked Exception (aka RuntimeException) - Very often a programming error such as a NullPointerExceptionor an illegal argument. Applications can sometimes handle or recover from this Throwablecategory -- or at least catch it at the Thread's run()method, log the complaint, and continue running.
  • Checked Exception (aka Everything else) - Applications are expected to be able to catch and meaningfully do something with the rest, such as FileNotFoundExceptionand TimeoutException...
  • Error- 出现了足够严重的错误,大多数应用程序应该崩溃而不是尝试处理问题,
  • Unchecked Exception (aka RuntimeException) - 通常是编程错误,例如 aNullPointerException或非法参数。应用程序有时可以处理或从这个Throwable类别中恢复——或者至少在 Thread 的run()方法中捕获它,记录投诉,然后继续运行。
  • Checked Exception (aka Everything else) - 应用程序应该能够捕获并有意义地处理其余部分,例如FileNotFoundExceptionTimeoutException...

回答by Robin

Errors tend to signal the end of your application as you know it. It typically cannot be recovered from and should cause your VM to exit. Catching them should not be done except to possibly log or display and appropriate message before exiting.

正如您所知,错误往往表示应用程序结束。它通常无法恢复,并且会导致您的 VM 退出。除了在退出之前可能记录或显示适当的消息外,不应捕获它们。

Example: OutOfMemoryError- Not much you can do as your program can no longer run.

示例:OutOfMemoryError- 由于程序无法再运行,您无能为力。

Exceptions are often recoverable and even when not, they generally just mean an attempted operation failed, but your program can still carry on.

异常通常是可恢复的,即使不能恢复,它们通常也只是意味着尝试操作失败,但您的程序仍然可以继续运行。

Example: IllegalArgumentException- Passed invalid data to a method so that method call failed, but it does not affect future operations.

示例:IllegalArgumentException- 将无效数据传递给方法,因此方法调用失败,但不影响以后的操作。

These are simplistic examples, and there is another wealth of information on just Exceptions alone.

这些只是简单的例子,另外还有大量关于异常的信息。

回答by Powerlord

Sun puts it best:

Sun说得最好

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.

Error 是 Throwable 的一个子类,它指示合理的应用程序不应尝试捕获的严重问题。

回答by Tobias Müller

The description of the Errorclass is quite clear:

Error类的描述很清楚:

An Erroris a subclass of Throwablethat indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeatherror, though a "normal" condition, is also a subclass of Errorbecause most applications should not try to catch it.

A method is not required to declare in its throws clause any subclasses of Errorthat might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.

AnError是一个子类Throwable,表示合理的应用程序不应尝试捕获的严重问题。大多数此类错误是异常情况。该ThreadDeath错误虽然是“正常”条件,但也是 的一个子类,Error因为大多数应用程序不应尝试捕获它。

方法不需要在它的 throws 子句中声明在Error方法执行期间可能抛出但未被捕获的任何子类 ,因为这些错误是不应该发生的异常情况。

Cited from Java's own documentation of the class Error.

引用自 Java 自己的类文档Error

In short, you should not catch Errors, except you have a good reason to do so. (For example to prevent your implementation of web server to crash if a servlet runs out of memory or something like that.)

简而言之,您不应该 catch Errors,除非您有充分的理由这样做。(例如,如果 servlet 内存不足或类似情况,防止您的 Web 服务器实现崩溃。)

An Exception, on the other hand, is just a normal exception as in any other modern language. You will find a detailed description in the Java API documentation or any online or offline resource.

Exception另一方面,An只是任何其他现代语言中的正常例外。您可以在 Java API 文档或任何在线或离线资源中找到详细说明。

回答by egaga

Here's a pretty good summary from Java API what an Error and Exception represents:

这是来自 Java API 的一个很好的总结,错误和异常代表什么:

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.

A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.

Error 是 Throwable 的一个子类,它指示合理的应用程序不应尝试捕获的严重问题。大多数此类错误是异常情况。ThreadDeath 错误虽然是“正常”情况,但也是 Error 的一个子类,因为大多数应用程序不应该尝试捕获它。

一个方法不需要在它的 throws 子句中声明在方法执行期间可能抛出但没有被捕获的 Error 的任何子类,因为这些错误是不应该发生的异常情况。

OTOH, for Exceptions, Java API says:

OTOH,对于异常,Java API 说:

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.

Exception 类及其子类是 Throwable 的一种形式,它指示合理的应用程序可能想要捕获的条件。

回答by Mr. Will

IMO an error is something that can cause your application to fail and should not be handled. An exception is something that can cause unpredictable results, but can be recovered from.

IMO 错误是可能导致您的应用程序失败并且不应处理的事情。异常是可能导致不可预测的结果,但可以从中恢复的情况。

Example:

例子:

If a program has run out of memory it is an error as the application cannot continue. However, if a program accepts an incorrect input type it is an exception as the program can handle it and redirect to receive the correct input type.

如果程序内存不足,则会出现错误,因为应用程序无法继续。但是,如果程序接受不正确的输入类型,则它是一个例外,因为程序可以处理它并重定向以接收正确的输入类型。

回答by user2485429

Errors are mainly caused by the environment in which application is running. For example, OutOfMemoryError occurs when JVM runs out of memory or StackOverflowError occurs when stack overflows.

错误主要是由应用程序运行的环境引起的。例如,当 JVM 内存不足时发生 OutOfMemoryError 或堆栈溢出时发生 StackOverflowError。

Exceptions are mainly caused by the application itself. For example, NullPointerException occurs when an application tries to access null object or ClassCastException occurs when an application tries to cast incompatible class types.

异常主要是由应用程序本身引起的。例如,当应用程序尝试访问空对象时会发生 NullPointerException,或者当应用程序尝试强制转换不兼容的类类型时会发生 ClassCastException。

Source : Difference Between Error Vs Exception In Java

来源:Java 中错误与异常的区别

回答by Mikhailov Valentine

There is several similarities and differences between classes java.lang.Exceptionand java.lang.Error.

java.lang.Exceptionjava.lang.Error.

Similarities:

相似之处:

  • First - both classes extends java.lang.Throwableand as a result inherits many of the methods which are common to be used when dealing with errors such as: getMessage, getStackTrace, printStackTraceand so on.

  • Second, as being subclasses of java.lang.Throwablethey both inherit following properties:

    • Throwable itself and any of its subclasses (including java.lang.Error) can be declared in method exceptions list using throwskeyword. Such declaration required only for java.lang.Exceptionand subclasses, for java.lang.Throwable, java.lang.Errorand java.lang.RuntimeExceptionand their subclasses it is optional.

    • Only java.lang.Throwableand subclasses allowed to be used in the catchclause.

    • Only java.lang.Throwableand subclasses can be used with keyword - throw.

  • 首先-这两个类延伸java.lang.Throwable,并与错误,如处理时要使用很多都是常见的方法,结果继承:getMessagegetStackTraceprintStackTrace等。

  • 其次,作为它们的子类,java.lang.Throwable它们都继承了以下属性:

    • Throwable 本身及其任何子类(包括java.lang.Error)可以使用throws关键字在方法异常列表中声明。只需要对这样的声明java.lang.Exception和子类,对java.lang.Throwablejava.lang.Errorjava.lang.RuntimeException及其子类是可选的。

    • java.lang.Throwable子类中只允许使用和子类catch

    • 只有java.lang.Throwable和 子类可以与关键字 - 一起使用throw

The conclusion from this property is following both java.lang.Errorand java.lang.Exceptioncan be declared in the method header, can be in catchclause, can be used with keyword throw.

这个属性的结论是在两者之后java.lang.Errorjava.lang.Exception可以在方法头中声明,可以在catch子句中,可以与关键字一起使用throw

Differences:

区别:

  • First - conceptual difference: java.lang.Errordesigned to be thrown by the JVM and indicate serious problems and intended to stop program execution instead of being caught(but it is possible as for any other java.lang.Throwablesuccessor).

    A passage from javadocdescription about java.lang.Error:

    ...indicates serious problems that a reasonable application should not try to catch.

    In opposite java.lang.Exceptiondesigned to represent errors that expected and can be handled by a programmer without terminating program execution.

    A passage from javadocdescription about java.lang.Exception:

    ...indicates conditions that a reasonable application might want to catch.

  • The second difference between java.lang.Errorand java.lang.Exceptionthat first considered to be a uncheckedexception for compile-time exception checking. As the result code throwing java.lang.Erroror its subclasses don't require to declare this error in the method header. While throwing java.lang.Exceptionrequired declaration in the method header.
  • 第一个 - 概念差异:java.lang.Error设计为由 JVM 抛出并指示严重问题,旨在停止程序执行而不是被捕获(但对于任何其他java.lang.Throwable后继者也是可能的)。

    一段来自javadoc 的描述java.lang.Error

    ...表示合理的应用程序不应该试图捕捉的严重问题。

    相反,java.lang.Exception旨在表示程序员可以在不终止程序执行的情况下处理的预期错误。

    一段来自javadoc 的描述java.lang.Exception

    ...表示合理的应用程序可能想要捕获的条件。

  • java.lang.Errorjava.lang.Exception第一个被认为是编译时异常检查的未检查异常之间的第二个区别。由于结果代码抛出java.lang.Error或其子类不需要在方法头中声明此错误。在java.lang.Exception方法头中抛出必需的声明时。

Throwable and its successor class diagram (properties and methods are omitted). enter image description here

Throwable 及其后继类图(属性和方法省略)。 在此处输入图片说明

回答by avandeursen

This slide showing Java's exception hierarchyby @georgios-gousiosconcisely explains the differences between Errors and Exceptions in Java.

这张由@georgios-gousios 制作的展示Java 异常层次结构的幻灯片简洁地解释了Java 中错误和异常之间的区别。

Java Exception Hierarchy

Java 异常层次结构

回答by roottraveller

Errors-

错误-

  1. Errors in java are of type java.lang.Error.
  2. All errors in java are unchecked type.
  3. Errors happen at run time. They will not be known to compiler.
  4. It is impossible to recover from errors.
  5. Errors are mostly caused by the environment in which application is running.
  6. Examples :java.lang.StackOverflowError, java.lang.OutOfMemoryError
  1. Errorjava 中的 s 是类型java.lang.Error
  2. java中的所有错误都是未经检查的类型。
  3. Errors 发生在运行时。它们不会被编译器知道。
  4. 从错误中恢复是不可能的。
  5. Errors 主要是由应用程序运行的环境引起的。
  6. 例子:java.lang.StackOverflowErrorjava.lang.OutOfMemoryError

Exceptions-

例外——

  1. Exceptions in java are of type java.lang.Exception.
  2. Exceptions include both checked as well as unchecked type.
  3. Checked exceptions are known to compiler where as unchecked exceptions are not known to compiler because they occur at run time.
  4. You can recover from exceptions by handling them through try-catchblocks.
  5. Exceptions are mainly caused by the application itself.
  6. Examples :Checked Exceptions : SQLException, IOException
    Unchecked Exceptions : ArrayIndexOutOfBoundException, ClassCastException, NullPointerException
  1. Exceptionjava 中的 s 是类型java.lang.Exception
  2. Exceptions 包括选中和未选中的类型。
  3. 编译器知道已检查异常,而编译器不知道未检查异常,因为它们发生在运行时。
  4. 您可以通过try-catch块处理异常来从异常中恢复。
  5. Exceptions 主要是由应用程序本身引起的。
  6. 例如:检查异常:SQLExceptionIOException
    unchecked异常:ArrayIndexOutOfBoundExceptionClassCastExceptionNullPointerException

further reading : http://javaconceptoftheday.com/difference-between-error-vs-exception-in-java/http://javaconceptoftheday.com/wp-content/uploads/2015/04/ErrorVsException.png

进一步阅读:http: //javaconceptoftheday.com/difference-between-error-vs-exception-in-java/http://javaconceptoftheday.com/wp-content/uploads/2015/04/ErrorVsException.png