First find out the relationship between the three of them. Both
Exception inherit from
RuntimeException inherits from
In Java, only instances of the Throwable type can be thrown (throw) or caught (catch).
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
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,
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.