The operating environment of this tutorial: Windows 7 system, Java 10 version, DELL G3 computer.
1. Description
(1) For runtime exceptions, they can be handled without explicit
(2) For compile-time exceptions, they must be handled explicitly
2. Method 1:
try{ //Code that may cause exception}catch(Exption1 e1){ // Processing method one}catch(Exption2 e2){ // Processing method two}finally{ // Code that must be executed}
Note:
(1) Variables declared in try are similar to local variables. Except for the try{} statement, they cannot be called.
(2) Inside the catch statement is the processing of exception objects: e.getMessage(); e.printStackTrace()
(3) Multiple catch statements can be used. The exception class object thrown in try matches the type of exception class in catch from top to bottom. Once satisfied, the code in catch will be executed. After execution, the following multiple statements will be jumped out. catch statement
(4) If the exception is handled, the subsequent code continues to execute
(5) If the multiple exception types in the catch are in a "parallel" relationship, then the order can be either before or after. If the multiple exception types in the catch are in an "inclusive" relationship, the subclass must be placed before the parent class for processing. Otherwise Report an error
(6) finally is optional
(7) Finally stores code that will definitely be executed regardless of whether there are still unhandled exceptions in try or catch, and whether there is a return statement.
(8) try-catch can be nested in each other
3. Method 2:
(1) At the declaration of the method, explicitly throw the type of the exception object
(2) Format, such as:
public static void method() throws Exception{}
(3) When an exception occurs inside this method, an object of the exception class will be thrown to the caller of the method.
(4) Exception objects can be thrown upward layer by layer until main. Of course, during the upward throwing process, it can be processed through try-catch-finally.
The above is the classification solution of Java exception handling. I hope it can be helpful to everyone. More Java learning guide: java tutorial