简体   繁体   English

未经检查的异常或运行时异常之间的区别

[英]Difference between Unchecked exception or runtime exception

This was an interview question.这是一道面试题。 What is the main difference between unchecked exception and error as both are not caught?未经检查的异常和错误之间的主要区别是什么,因为两者都没有被捕获? They will terminate the program.他们将终止该计划。

As stated by their name, unchecked exceptions are not checked at compile-time which means that the compiler doesn't require methods to catch or to specify (with a throws ) them.正如其名称所述,未检查异常在编译时不会检查,这意味着编译器不需要方法来捕获或指定(使用throws )它们。 Classes belonging to this category are detailed in the section 11.2 Compile-Time Checking of Exceptions of the JLS:属于此类别的类在第11.2编译时检查JLS 的异常中有详细说明:

The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses .未经检查的异常类是类RuntimeException及其子类,以及类Error及其子类 All other exception classes are checked exception classes .所有其他异常类都是检查异常类 The Java API defines a number of exception classes, both checked and unchecked. Java API 定义了许多异常类,包括检查的和未检查的。 Additional exception classes, both checked and unchecked, may be declared by programmers.程序员可以声明额外的异常类,包括检查的和未检查的。 See §11.5 for a description of the exception class hierarchy and some of the exception classes defined by the Java API and Java virtual machine.有关异常类层次结构和一些由 Java API 和 Java 虚拟机定义的异常类的描述,请参见第11.5 节

The following picture illustrates the Exception hierarchy:下图说明了异常层次结构:

替代文字

The class Error and its subclasses are exceptions from which ordinary programs are not ordinarily expected to recover and, as explained in 11.5 The Exception Hierarchy :Error及其子类是普通程序通常不会从中恢复的异常,如11.5 The Exception Hierarchy 中所述

The class Error is a separate subclass of Throwable , distinct from Exception in the class hierarchy, to allow programs to use the idiom:ErrorThrowable一个单独子类,在类层次结构中与Exception不同,以允许程序使用习语:

 } catch (Exception e) {

to catch all exceptions from which recovery may be possible without catching errors from which recovery is typically not possible.捕获可以恢复的所有异常,而不捕获通常无法恢复的错误。

To summarize, RuntimeException are a subset of unchecked exceptions for exceptions from which recovery is possible (but unchecked exception is not a synonym of RuntimeException as many are answering here).总而言之, RuntimeException是可以从中恢复的异常的未经检查异常的子集(但未经检查的异常不是RuntimeException的同义词,因为许多人在这里回答)。

The JavaDocs sum these up pretty well. JavaDocs 很好地总结了这些。

java.lang.RuntimeException : java.lang.RuntimeException :

RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. RuntimeException 是那些在 Java 虚拟机正常运行期间可以抛出的异常的超类。

A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.方法不需要在它的 throws 子句中声明在方法执行期间可能抛出但未被捕获的 RuntimeException 的任何子类。

java.lang.Error : java.lang.Error :

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Error 是 Throwable 的一个子类,它指示合理的应用程序不应尝试捕获的严重问题。 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. ThreadDeath 错误虽然是“正常”情况,但也是 Error 的一个子类,因为大多数应用程序不应该尝试捕获它。

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

Note that "unchecked exception" is merely a synonym for a RuntimeException .请注意,“未经检查的异常”只是RuntimeException的同义词。

Note: a RuntimeException IS an unchecked exception注意:RuntimeException 是未经检查的异常

An unchecked exception would be one that is known to be possible at a point in the execution but is not caught, for example a NullPointerException is always a possibility if you don't check for them and will cause your program to terminate.未经检查的异常是已知在执行中的某个点可能发生但未被捕获的异常,例如,如果您不检查它们,NullPointerException 总是可能的,并且会导致您的程序终止。 You could check for it by wrapping code in try-catch, but this is not enforced (unlike a checked exception that will enforce that the exception is handled in some way).您可以通过在 try-catch 中包装代码来检查它,但这不是强制执行的(与强制以某种方式处理异常的已检查异常不同)。

An error is something that can occur at any point during execution and can't really be caught because it is not eplicitly caused by a particular method call etc. For example an OutOfMemoryError or a StackOverflowError.错误是在执行过程中的任何时候都可能发生的事情,并且不能真正被捕获,因为它不是由特定方法调用等引起的。例如 OutOfMemoryError 或 StackOverflowError。 Both of these could occur at any time and will cause your application to terminate.这两种情况都可能随时发生,并会导致您的应用程序终止。 Catching these errors make no sense as they indicate that something has happened that you won't be able to recover from.捕捉这些错误毫无意义,因为它们表明发生了一些您无法恢复的事情。

Errors indicate fundamental problems that should never occur.错误表明根本不应该发生的问题。 If you run into an error s.th.如果您遇到错误 s.th. really bad happened.真的很糟糕发生了。
Unchecked Exceptions (Runtime Exceptions) on the other hand are used whenever an exception could be expected somehow but there is no reasonable way to deal with it then and thus a try catch statement would be just annoying and a waste of space.另一方面,只要以某种方式可以预期异常,就会使用未经检查的异常(运行时异常),但没有合理的方法来处理它,因此 try catch 语句只会令人讨厌并浪费空间。

Checked Exception:检查异常:

  • The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions.除了RuntimeExceptionError之外,扩展Throwable类的类称为检查异常。
  • Also known as compile time exception because these type of exceptions are checked at compile time.也称为编译时异常,因为这些类型的异常是在编译时检查的。 That means if we ignore these exception (not handled with try/catch or throw the exception) then a compilation error occurred.这意味着如果我们忽略这些异常(不使用try/catch处理或throw异常),则发生编译错误。
  • They are programmatically recoverable problems which are caused by unexpected conditions outside control of code (eg database down, file I/O error, wrong input, etc)它们是由代码控制之外的意外情况(例如数据库关闭、文件 I/O 错误、错误输入等)引起的可通过编程方式恢复的问题
  • We can avoid them using try/catch block.我们可以使用try/catch块来避免它们。
  • Example: IOException , SQLException etc示例: IOExceptionSQLException

Unchecked Exception:未经检查的异常:

  • The classes that extend RuntimeException are known as unchecked exceptions扩展RuntimeException的类称为未经检查的异常
  • Unchecked exceptions are not checked at compile-time rather they are checked at runtime.And thats why they are also called "Runtime Exception"未经检查的异常不在编译时检查,而是在运行时检查。这就是为什么它们也被称为“运行时异常”
  • They are also programmatically recoverable problems but unlike checked exception they are caused by faults in code flow or configuration.它们也是可通过编程方式恢复的问题,但与检查异常不同,它们是由代码流或配置中的错误引起的。
  • Example: ArithmeticException , NullPointerException , ArrayIndexOutOfBoundsException etc示例: ArithmeticExceptionNullPointerExceptionArrayIndexOutOfBoundsException
  • Since they are programming error, they can be avoided by nicely/wisely coding.由于它们是编程错误,因此可以通过良好/明智的编码来避免它们。 For example "dividing by zero" occurs ArithmeticEceeption .例如,“除以零”发生ArithmeticEceeption We can avoid them by a simple if condition - if(divisor!=0) .我们可以通过一个简单的 if 条件来避免它们 - if(divisor!=0) Similarly we can avoid NullPointerException by simply checking the references - if(object!=null) or using even better techniques同样,我们可以通过简单地检查引用来避免NullPointerException - if(object!=null)或使用更好的技术

Error:错误:

  • Error refers irrecoverable situation that are not being handled by try/catch Error指的是 try/catch 没有处理的不可恢复的情况
  • Example: OutOfMemoryError , VirtualMachineError , AssertionError etc.示例: OutOfMemoryErrorVirtualMachineErrorAssertionError等。

Error : These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from.错误:这些是应用程序外部的异常情况,应用程序通常无法预测或从中恢复。

Runtime exception : These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from.运行时异常:这些是应用程序内部的异常情况,应用程序通常无法预测或从中恢复。

You may want to read this :您可能想阅读以下内容

Errors and runtime exceptions are collectively known as unchecked exceptions.错误和运行时异常统称为未检查异常。

runtime exceptions are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from.运行时异常是应用程序内部的异常情况,应用程序通常无法预测或从中恢复。 These usually indicate programming bugs, such as logic errors or improper use of an API这些通常表示编程错误,例如逻辑错误或 API 使用不当

You may want to take a look at this link which explains the Three Kinds of Exceptions.您可能想看看这个链接,它解释了三种异常。

http://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html http://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html

I hope this helps.我希望这有帮助。

RuntimeExceptions and Errors like OutOfMemoryError don't need to be catched and can be thrown until they reach main() which will terminate the application. RuntimeExceptions和像OutOfMemoryError这样的错误不需要被捕获并且可以被抛出,直到它们到达将终止应用程序的 main() 。

Other Exceptions cause an compile error if they are not catched or included in the throws list.如果其他异常未被捕获或未包含在 throws 列表中,则会导致编译错误。

Both java.lang.Error and java.lang.Exception are the sub classes of java.lang.Throwable. java.lang.Error和java.lang.Exception都是java.lang.Throwable的子类。

java.lang.Error class represents the errors which are mainly caused by the environment in which application is running. java.lang.Error class表示主要由应用程序运行环境引起的错误。 For example, OutOfMemoryError occurs when JVM runs out of memory or StackOverflowError occurs when stack overflows.例如,当 JVM 用完 memory 时会发生 OutOfMemoryError,或者当堆栈溢出时会发生 StackOverflowError。

Where as java.lang.Exception class represents the exceptions which are mainly caused by the application itself.其中 java.lang.Exception class 表示主要由应用程序本身引起的异常。 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 在应用程序尝试访问 null object 时发生,或者 ClassCastException 在应用程序尝试转换不兼容的 class 类型时发生。

All the sub classes of java.lang.Exception (except sub classes of RunTimeException) are checked exceptions. java.lang.Exception的所有子类(RunTimeException的子类除外)都是检查异常。 For example, FileNotFoundException, IOException, SQLException, ClassNotFoundException etc…例如,FileNotFoundException、IOException、SQLException、ClassNotFoundException 等……

All the sub classes of java.lang.RuntimeException and java.lang.Error are unchecked exceptions. java.lang.RuntimeException 和 java.lang.Error 的所有子类都是未经检查的异常。 For example, NullPointerException, ArithmeticException, ClassCastException, ArrayIndexOutOfBoundsException, StackOverflowError, OutOfMemoryError etc…例如,NullPointerException、ArithmeticException、ClassCastException、ArrayIndexOutOfBoundsException、StackOverflowError、OutOfMemoryError 等……

Source: Error Vs Exceptions , Checked Vs Unchecked Exceptions资料来源: 错误与异常已检查与未检查的异常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM