The difference between Error, Exception and RuntimeException

created at 08-18-2021 views: 43

First find out the relationship between the three of them. Both Error and Exception inherit from Throwable, while RuntimeException inherits from Exception

In Java, only instances of the Throwable type can be thrown (throw) or caught (catch).

relation of Error, Exception and RuntimeException

Error and Exception reflect the classification of different abnormal situations by the designers of the Java platform. Exception is an unexpected situation that can be expected in the normal operation of the program, which may and should be caught and dealt with accordingly. Error refers to a situation that is unlikely to occur under normal circumstances. Most errors will cause the program (such as JVM) to be in an abnormal and unrecoverable state. Since it is an abnormal situation, it is inconvenient and does not need to be captured. Common ones are OutOfMemoryError, which is a subclass of Error.

There is a classic question: What is the difference between NoClassDefFoundError and ClassNotFoundException? Correct answer: NoClassDefFoundError is thrown when the Java virtual machine or ClassLoader instance tries to load a certain class, but the definition of the class cannot be found; ClassNotFoundException is when the application tries to call Class.forName(String) to load the class by string name , And the exception thrown when the class definition is not found.

Exception is divided into checked exception and unchecked exception. All subclasses of RuntimeException are unchecked exceptions; the remaining subclasses of Exception are checked exceptions. The so-called "checked exception" means that the source code example must be explicitly captured, which is part of the compile-time check. In other words, when you see that a checked exception may be thrown in a method declaration, then as the caller, you must consider how to handle this exception, otherwise the compiler will give an error message.

The so-called "unchecked exception" is usually a logical error that can be avoided by coding. It is determined whether or not it needs to be caught according to the specific needs, and it will not be mandatory at compile time. For example, NullPointerException, ArrayIndexOutOfBoundsException, etc. In other words, the programmer should try to avoid such exceptions in the program through reasonable coding, or it is the programmer's responsibility to make such exceptions in the program.

created at:08-18-2021
edited at: 08-18-2021: