1. Classification of anomalies
1.1 Throwable
All exceptions in Java inherit from Java The lang. throwable class represents a class that can be thrown
Throwable is a common method of the top-level parent class:
1. Returns the details when the exception occurred public string getMessage(); 2. Returns a brief description of when the exception occurred public string toString(); 3. Returns the localization information of the exception object. use Throwable Subclasses that override this method can claim localization information. If the subclass does not override the method, the information returned by the method is the same as getMessage()The results returned are the same public string getLocalizedMessage(); 4. Print on console Throwable Object encapsulated exception information public void printStackTrace();
1.2 exception and Error
Exception and Error are two important subclasses of Thorwable:
Exception indicates exception and Error indicates Error
1.2.1 Error
definition:
An error that cannot be handled by the program indicates a more serious problem in the operation of the program;
There is usually a virtual machine error. For example, when the jvm runs out of available memory, an OutOfMemoryError (OOM) will appear
When such errors occur, the JVM will generally terminate the thread,
1.2.2 Exception
definition:
Exceptions that the program itself can handle;
Classification:
- Runtime exception: (RuntimeException) this kind of exception can not be caught when writing code; For example: nullpotiterexception (null pointer exception)
- Non runtime exception: this kind of exception must be caught when writing code, otherwise it cannot be compiled; For example: FileNotFoundException (exception not found in file)
2. Exception handling
2.1 Throw, Thorws
2.1.1throw
The throw keyword is used inside the method to throw out exceptions. When the program reaches this step, an error will be reported,
Once throw is executed, the program will immediately turn to the exception handling stage, the following statements will not be executed, and the method will no longer return meaningful values!
public void m1(){ if(a > 0){ throw new NullPointerException(); } }
2.1.2 throws
The throws keyword is used on the method to throw the program to the caller
If you don't want any exception handling in a method, you must declare all possible exceptions to the method when there is no code for exception handling
(in fact, if you don't want to deal with it by yourself, then leave it to others. Tell others what will happen to me, report my own fault and let others deal with it)
If a method may have an exception, but it is unable to handle such an exception, you can declare and throw an exception with the throws clause in the method declaration.
For example, when the car is running, there may be a fault. If the car itself can't handle the fault, let the driver handle it.
public void m1() throws NullPointException,FileNotFoundException{ }
- It should be noted that:
- throw is to handle the exception yourself
- throws is to throw the exception to the caller
2.2 capture try
Syntax:
try { // Program code where exceptions may occur } catch (Type1 id1){ // Catch and handle the exception type Type1 thrown by try } catch (Type2 id2){ //Catch and handle the exception type Type2 thrown by try }finally { // The block of statements that will be executed regardless of whether an exception occurs }
Execution sequence:
Execution order of try, catch and finally statement blocks:
1) When try does not catch exceptions: the statements in the try statement block are executed one by one, and the program will skip the catch statement block and execute the finally statement block and subsequent statements;
2) When an exception is caught in the try, the exception is not handled in the catch statement block: the exception will be thrown to the JVM for processing, and the statements in the finally statement block will still be executed, but the statements after the finally statement block will not be executed;
3) When an exception is caught in a try, the exception is handled in the catch statement block: it is executed in order in the try statement block. When an exception occurs in the execution of a certain statement, the program will jump to the catch statement block and match it with the catch statement block one by one to find the corresponding processing program. Other catch statement blocks will not be executed, but in the try statement block, The statements after the exception will not be executed. After the catch statement block is executed, the statements in the finally statement block will be executed, and finally the statements after the finally statement block will be executed.
Note: finally not implemented
Finally block: the statements in the finally block will be executed whether or not exceptions are caught or handled. When a return statement is encountered in a try or catch block, the finally statement block will be executed before the method returns.
finally blocks will not be executed in the following four special cases:
1) An exception occurred in a finally statement block.
2) System. Is used in the previous code Exit() exits the program.
3) The thread on which the program is located dies.
4) Turn off the CPU.
3. Custom exception
Custom exception format:
public class MyException extends RuntimeException { public MyException() { } public MyException(String message) { super(message); } public MyException(String message, Throwable cause) { super(message, cause); } public MyException(Throwable cause) { super(cause); } public MyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } } /* a.Output abnormal information getMessage() b.Output more detailed information that causes the exception printStackTrace() */
4. try...catch...finally
About try catch... Finally execution order
1. Return only in try
public static int m1() { int a = 10; try { System.out.println("try - " + a); return a; } catch (Exception e) { System.out.println("catch - " + a); return a = 20; } finally { a = 15; System.out.println("finall - " + a); } } public static void main(String[] args) { System.out.println("main - " + m1()); } /* Execution result: try - 10 finall - 15 main - 10 */
Statement was executed in finally, but the value of a was not changed.
Explanation:
The code is executed sequentially from try to finally. Since finally will be executed anyway, the statements in try will not be returned directly.
In the return block of the try statement, the reference variable returned by return is not the reference variable a defined outside the try statement,
Instead, the system redefines a local reference a1, which points to the value corresponding to reference a, that is, 10, even if reference a points to the value 15 in the finally statement,
Because the reference returned by return is no longer a but a1, the value of reference a has nothing to do with the return value in the try statement.
2. Return in finally
public static int m1() { int a = 10; try { System.out.println("try - " + a); return a; } catch (Exception e) { System.out.println("catch - " + a); return a = 20; } finally { a = 15; System.out.println("finall - " + a); return a; } } public static void main(String[] args) { System.out.println("main - " + m1()); } /* Execution result: try - 10 finall - 15 main - 15 */ -- Here is to change the return value
As you can see, it is returned from the finally statement block. It can be seen that the JVM ignores the return statement in the try
3. The return value is an array or a collection
public static List m1() { List<String> strList = new ArrayList<>(); try { strList.add("try"); System.out.println("try - "); return strList; } catch (Exception e) { strList.add("catch"); System.out.println("catch - "); return strList; } finally { strList.add("finally"); System.out.println("finall - "); return strList; } } public static void main(String[] args) { System.out.println("main - " + m1()); } /* Execution result: try - finall - main - [try, finally] */
4. Summary:
1. finally statements are always executed
2. If there is a return statement in try and catch, but there is no return in finally, modifying the data except the wrapper type, static variable and global variable in finally will not have any impact on the variables returned in try and catch (the wrapper type and static variable will change, * global variable *)
3. Try not to use the return statement in finally. If it is used, the return statements in try and catch and the exceptions in try and catch will be ignored, which shields the occurrence of errors
4. Avoid throwing exceptions again in finally. Once an exception occurs in finally, the code execution will throw the exception information in finally, and the exceptions in try and catch will be ignored
Therefore, in actual projects, finally is often used to close the stream or database resources without additional operations.