Abnormal classification
Exceptions are mainly divided into exception and error, and their inheritance relationship is as follows:
Throwable is the root of the exception system, which is inherited from Object. Throwable has two systems: Error and Exception
Error
Error means a serious Error that the program cannot do anything about. For example:
OutOfMemoryError: Memory is exhausted. NoClassDefFoundError: a Class cannot be loaded. StackOverflowError: stack overflow
Exception
Exceptions are runtime errors that can be caught and handled.
Logical processing
Some exceptions are part of your application’s logical processing and should be caught and handled. Such as:
NumberFormatException: format error of numeric type FileNotFoundException: file not found SocketException: failed to read the network
Application error
Other exceptions are the result of incorrect programming logic and should be fixed by the program itself. Such as:
NullPointerException: for a null object IndexOutOfBoundsException: call a method or field array index of crossing the line
classification
Runtime exception
Runtime exceptions are RuntimeExceptions and their subclasses;
Non-runtime exception
A runtime exception is actually RuntimeException (including IOException, ReflectiveOperationException, etc.)
Java rules
- Exceptions that must be caught, including Exception and its subclasses, but not RuntimeException and its subclasses, are called Checked Exceptions.
- Exceptions that do not need to be caught include Error and its subclasses, RuntimeException and its subclasses.
Exception handling
try catch
As you know, try catch is a classic way to catch exceptions in Java.
try {
// Execute code with possible exceptions. Once an exception is found, it immediately jumps to catch execution. Otherwise nothing in the catch will be executed
} catch(Exception e) {// This code will not execute unless an exception occurs in the code executing the try
}
//finally is optional
finally {
// Finally is executed whenever a try or catch is executed
}
Copy the code
Pay attention to
- Do not put a return inside a try, because if you put a return, you will not throw an exception
- When you throw an exception, try to narrow the scope of the exception to make sure you see the exception and know what the problem is, rather than just an exception
- A return in finally overwrites a return ina catch
Reference:
- Teacher Liao Xuefeng website
- Novice tutorial
- Why technology – Abnormal message suddenly gone