java.lang.RuntimeException 和 java.lang.Exception 的区别

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

Difference between java.lang.RuntimeException and java.lang.Exception

javaexception

提问by cchampion

Someone please explain the difference between java.lang.RuntimeExceptionand java.lang.Exception? How do I decide which one to extend if I create my own exception?

有人请解释之间的差异java.lang.RuntimeExceptionjava.lang.Exception?如果我创建自己的异常,如何决定扩展哪一个?

采纳答案by fastcodejava

Generally RuntimeExceptionsare exceptionsthat can be prevented programmatically. E.g NullPointerException, ArrayIndexOutOfBoundException. If you check for nullbefore calling any method, NullPointerExceptionwould never occur. Similarly ArrayIndexOutOfBoundExceptionwould never occur if you check the index first. RuntimeExceptionare not checked by the compiler, so it is clean code.

通常,RuntimeExceptions是可以通过编程方式防止的异常。例如 NullPointerExceptionArrayIndexOutOfBoundException。如果null在调用任何方法之前进行检查,则NullPointerException永远不会发生。ArrayIndexOutOfBoundException如果您先检查索引,同样不会发生。RuntimeException不被编译器检查,所以它是干净的代码。

EDIT: These days people favor RuntimeExceptionbecause the clean code it produces. It is totally a personal choice.

编辑:现在人们喜欢RuntimeException它,因为它产生的代码干净。这完全是个人选择。

回答by Lawrence Dol

An Exception is checked, and a RuntimeException is unchecked.

检查 Exception ,未检查 RuntimeException 。

Checked means that the compiler requires that you handle the exception in a catch, or declare your method as throwing it (or one of its superclasses).

Checked 意味着编译器要求您在 catch 中处理异常,或者将您的方法声明为抛出它(或其超类之一)。

Generally, throw a checked exception if the caller of the API is expected to handle the exception, and an unchecked exception if it is something the caller would not normally be able to handle, such as an error with one of the parameters, i.e. a programming mistake.

通常,如果 API 的调用者需要处理异常,则抛出已检查的异常,如果调用者通常无法处理异常,则抛出未检查的异常,例如参数之一的错误,即编程错误。

回答by Andy White

In Java, there are two types of exceptions: checked exceptions and un-checked exceptions. A checked exception must be handled explicitly by the code, whereas, an un-checked exception does not need to be explicitly handled.

在 Java 中,有两种类型的异常:已检查异常和未检查异常。检查异常必须由代码显式处理,而未检查异常不需要显式处理。

For checked exceptions, you either have to put a try/catch block around the code that could potentially throw the exception, or add a "throws" clause to the method, to indicate that the method might throw this type of exception (which must be handled in the calling class or above).

对于已检查的异常,您必须在可能抛出异常的代码周围放置一个 try/catch 块,或者在方法中添加一个“throws”子句,以指示该方法可能会抛出此类异常(必须是在调用类或更高版本中处理)。

Any exception that derives from "Exception" is a checked exception, whereas a class that derives from RuntimeException is un-checked. RuntimeExceptions do not need to be explicitly handled by the calling code.

派生自“Exception”的任何异常都是已检查的异常,而派生自 RuntimeException 的类是未检查的。RuntimeExceptions 不需要由调用代码显式处理。

回答by sateesh

The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking, since the compiler cannot establish that run-time exceptions cannot occur. (from JLS).

运行时异常类(RuntimeException 及其子类)免于编译时检查,因为编译器无法确定不会发生运行时异常。(来自 JLS)。

In the classes that you design you should subclass Exceptionand throw instances of it to signal any exceptional scenarios. Doing so you will be explicitly signaling the clients of your class that usage of your class might throw exception and they have to take steps to handle those exceptional scenarios.

在您设计的类中,您应该子类化Exception并抛出它的实例以发出任何异常情况的信号。这样做,您将明确地向您的类的客户发出信号,说明您的类的使用可能会引发异常,并且他们必须采取措施来处理这些异常情况。

Below code snippets explain this point:

下面的代码片段解释了这一点:

//Create your own exception class subclassing from Exception
class MyException extends Exception {
    public MyException(final String message) {
        super(message);
    }
}

public class Process {
    public void execute() {
        throw new RuntimeException("Runtime");
    }  
    public void process() throws MyException {
        throw new MyException("Checked");
    }
}

In the above class definition of class Process, the method executecan throw a RuntimeExceptionbut the method declaration need not specify that it throws RuntimeException.

在类Process的上述类定义中,该方法execute可以抛出RuntimeException但方法声明不需要指定它抛出RuntimeException

The method processthrows a checked exception and it should declare that it will throw a checked exception of kind MyExceptionand not doing so will be a compile error.

该方法process抛出一个检查异常,它应该声明它将抛出一个MyException类型的检查异常,不这样做将是一个编译错误。

The above class definition will affect the code that uses Processclass as well.

上面的类定义也会影响使用Process类的代码。

The call new Process().execute()is a valid invocation where as the call of form new Process().process()gives a compile error. This is because the client code should take steps to handle MyException(say call to process() can be enclosed in a try/catch block).

调用new Process().execute()是一个有效的调用,因为表单调用 new Process().process()给出了编译错误。这是因为客户端代码应该采取措施来处理MyException(比如对 process() 的调用可以包含在 try/catch 块中)。

回答by GAJJE82

Before looking at the difference between java.lang.RuntimeExceptionand java.lang.Exceptionclasses, you must know the Exceptionhierarchy. Both Exceptionand Errorclasses are derived from class Throwable(which derives from the class Object). And the class RuntimeExceptionis derived from class Exception.

在查看java.lang.RuntimeExceptionjava.lang.Exception类之间的区别之前,您必须了解Exception层次结构。两个ExceptionError类都从类衍生的Throwable(其从类派生Object)。并且类RuntimeException是从类派生的Exception

All the exceptions are derived either from Exceptionor RuntimeException.

所有异常都源自ExceptionRuntimeException

All the exceptions which derive from RuntimeExceptionare referred to as uncheckedexceptions. And all the other exceptions are checkedexceptions. A checked exception must be caught somewhere in your code, otherwise, it will not compile. That is why they are called checked exceptions. On the other hand, with unchecked exceptions, the calling method is under no obligation to handle or declare it.

派生自的所有异常RuntimeException都称为未经检查的异常。所有其他异常都是检查异常。必须在代码中的某处捕获已检查的异常,否则将无法编译。这就是为什么它们被称为受检异常。另一方面,对于未经检查的异常,调用方法没有义务处理或声明它。

Therefore all the exceptions which compiler forces you to handle are directly derived from java.lang.Exceptionand all the other which compiler does not force you to handle are derived from java.lang.RuntimeException.

因此,编译器强制您处理的所有异常都是直接java.lang.Exception派生自java.lang.RuntimeException.

Following are some of the direct known subclasses of RuntimeException.

以下是RuntimeException 的一些直接已知子类。

AnnotationTypeMismatchException,
ArithmeticException,
ArrayStoreException,
BufferOverflowException,
BufferUnderflowException,
CannotRedoException,
CannotUndoException,
ClassCastException,
CMMException,
ConcurrentModificationException,
DataBindingException,
DOMException,
EmptyStackException,
EnumConstantNotPresentException,
EventException,
IllegalArgumentException,
IllegalMonitorStateException,
IllegalPathStateException,
IllegalStateException,
ImagingOpException,
IncompleteAnnotationException,
IndexOutOfBoundsException,
JMRuntimeException,
LSException,
MalformedParameterizedTypeException,
MirroredTypeException,
MirroredTypesException,
MissingResourceException,
NegativeArraySizeException,
NoSuchElementException,
NoSuchMechanismException,
NullPointerException,
ProfileDataException,
ProviderException,
RasterFormatException,
RejectedExecutionException,
SecurityException,
SystemException,
TypeConstraintException,
TypeNotPresentException,
UndeclaredThrowableException,
UnknownAnnotationValueException,
UnknownElementException,
UnknownTypeException,
UnmodifiableSetException,
UnsupportedOperationException,
WebServiceException 

回答by iberck

From oracle documentation:

从oracle文档:

Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

这是底线准则:如果可以合理地期望客户端从异常中恢复,请将其设为已检查异常。如果客户端无法从异常中恢复,请将其设为未经检查的异常。

Runtime exceptions represent problems that are the result of a programming problemand as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way.

运行时异常表示由编程问题导致的问题,因此,不能合理地期望 API 客户端代码从它们中恢复或以任何方式处理它们。

RuntimeExceptions are like "exceptions by invalid use of an api" examples of runtimeexceptions: IllegalStateException, NegativeArraySizeException, NullpointerException

运行时异常就像“无效使用 api 导致的异常”运行时异常的示例:IllegalStateException、NegativeArraySizeException、NullpointerException

With the Exceptions you must catch it explicitly because you can still do something to recover. Examples of Exceptions are: IOException, TimeoutException, PrintException...

对于异常,您必须明确捕获它,因为您仍然可以做一些事情来恢复。异常的例子有:IOException、TimeoutException、PrintException...

回答by Mahdi Esmaeili

Proper use of RuntimeException?

正确使用 RuntimeException?

From Unchecked Exceptions -- The Controversy:

来自未经检查的异常——争议

If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

如果可以合理地期望客户端从异常中恢复,请将其设置为已检查的异常。如果客户端无法从异常中恢复,请将其设为未经检查的异常。

Note that an unchecked exception is one derived from RuntimeExceptionand a checked exception is one derived from Exception.

请注意,未经检查的异常是从 派生的RuntimeException,已检查的异常是从 派生的Exception

Why throw a RuntimeExceptionif a client cannot do anything to recover from the exception? The article explains:

RuntimeException如果客户端无法从异常中恢复,为什么要抛出 a ?文章解释说:

Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.

运行时异常表示由编程问题导致的问题,因此,不能合理地期望 API 客户端代码从它们中恢复或以任何方式处理它们。此类问题包括算术异常,例如除以零;指针异常,例如尝试通过空引用访问对象;和索引异常,例如尝试通过太大或太小的索引访问数组元素。

回答by jayrhd

RuntimeException is a child class of Exception class

RuntimeException 是 Exception 类的子类

This is one of the many child classes of Exception class. RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. 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.

这是 Exception 类的众多子类之一。RuntimeException 是那些在 Java 虚拟机正常运行期间可以抛出的异常的超类。方法不需要在它的 throws 子句中声明在方法执行期间可能抛出但未被捕获的 RuntimeException 的任何子类。

The hierchy is

层次结构是

java.lang.Object

对象

---java.lang.Throwable

---java.lang.Throwable

-------java.lang.Exception

-------java.lang.Exception

-------------java.lang.RuntimeException

-------------java.lang.RuntimeException

回答by F.O.O

Exceptions are a good way to handle unexpected events in your application flow. RuntimeException are unchecked by the Compiler but you may prefer to use Exceptions that extend Exception Class to control the behaviour of your api clients as they are required to catch errors for them to compile. Also forms good documentation.

异常是处理应用程序流中意外事件的好方法。编译器未检查 RuntimeException,但您可能更喜欢使用扩展 Exception Class 的 Exceptions 来控制 api 客户端的行为,因为它们需要捕获错误以进行编译。也形成了良好的文档。

If want to achieve clean interface use inheritance to subclass the different types of exception your application has and then expose the parent exception.

如果要实现干净的接口,请使用继承对应用程序具有的不同类型的异常进行子类化,然后公开父异常。

回答by Joe Almore

In simple words, if your client/user can recover from the Exception then make it a CheckedException, if your client can't do anything to recover from the Exception then make it UncheckedRuntimeException. E.g, a RuntimeException would be a programmatic error, like division by zero, no user can do anything about it but the programmer himself, then it is a RuntimeException.

简而言之,如果您的客户/用户可以从 Exception 中恢复,则将其设为Checked Exception,如果您的客户无法从 Exception 中恢复,则将其设为Unchecked RuntimeException。例如,一个 RuntimeException 将是一个程序错误,就像被零除一样,除了程序员自己之外没有用户可以做任何事情,那么它就是一个RuntimeException