Exception overview and exception architecture
Exceptions can be divided into two categories:
Error: serious problems that cannot be solved by the Java virtual machine: JVM system internal errors, resource depletion and other serious situations. For example, StackOverflowError and OOM. Generally, targeted code is not written for processing
main(args);//Stack overflow Integer[] arr=new Integer[1024*1024*1024];//Heap overflow
Exception: for other general problems, you can write code to deal with them. Such as null pointer access, trying to read or write non-existent files, network connection interruption and array out of bounds. Generally, exception handling is only for
Including compile time exceptions (checked exceptions) and run-time exceptions (non checked exceptions)
Abnormal grasping and throwing model:
Process 1: Throw: once an exception occurs during the normal execution of the program, an object corresponding to the exception class will be generated at the exception code and thrown. Once the object is thrown, the subsequent code is no longer executed
Process 2: Catch: it can be understood as exception handling method: ① try catch finally ② throws
Generation of exception object:
- Automatically generated by the system
- Manually generated by the user (throws)
Common anomalies
Compile time exception
IOException: input / output stream exception
ClassnotFoundException:
The compiler will directly report an error when compiling an exception
Runtime exception
NullPointerException: null pointer exception
int[] arr=null; System.out.println(arr[3]);
ArrayIndexOutOfBoundsException: array subscript out of bounds
ClassCastException: type conversion error
Object obj=new Data(); String str=(String)obj;
NumberFormatException: numeric type conversion exception
String str="123"; str="abc"; int num=Integer.parseInt(str);
Inputmismatch exception: input matching exception
When an int is expected but a string is entered
Scanner scanner=new Scanner(System.in); int score=scanner.nextInt(); System.out.println(score);
ArithmeticException: arithmetic exception, such as dividing by 0
Exception handling mechanism: try catch finally
structure
try{ //Possible exception codes }catch(Exception type 1 variable name 1){ //How to handle exceptions }catch(Exception type 2 variable name 2){ //How to handle exceptions }catch(Exception type 2 variable name 2){ //How to handle exceptions } .... finally{ //Code that must execute }
instructions
public void test() { String str="223"; str="abc"; try { int num=Integer.parseInt(str); System.out.println("Normal execution"); }catch (NumberFormatException e) { System.out.println("Abnormal value conversion"); e.getMessage();//Get the thrown exception information, i.e. "exception" e.printStackTrace(); }catch(Exception e) { System.out.println("abnormal"); } }
- finally is optional
- Try is used to wrap the code with possible exceptions. Once an exception occurs in use, an exception type will be generated and matched in the catch. Once a catch is matched, the code in the corresponding catch will be executed for exception handling. If there is no finally, the try catch structure will jump out and the subsequent code will continue to be executed
- The exception type in catch. If there is no child parent relationship, the one who declares it on will execute first. If the child parent relationship is satisfied, the child class must be executed before the parent class, otherwise an error is reported
- Common exception object handling methods
e.getMessage();//Print the thrown exception information e.printStackTrace();//Print stack information, more commonly used
- The variable declared in the try structure cannot be called after the try structure
- Use the try catch structure to handle compile time exceptions, so that the program will no longer report errors at compile time, but errors may still be reported at run time, which is equivalent to delaying compile time exceptions until they appear at run time
- Since runtime exceptions are common in development, we usually do not write try catch finally for runtime exceptions. For compile time exceptions, try catch must be considered
finally
- finally, it is feasible
- finally, the code declared is bound to be executed. Even if there are exceptions in catch, exceptions in try, return statements, etc
- Resources such as database connection, input / output stream, network programming Socket and JVM cannot be recycled automatically. We need to release them manually. The resource release at this time needs to be declared in finally
Exception handling mechanism 2: throws
Structure:
throws: exception type
use
- The throws + exception type is written at the method declaration. Indicates the type of exception that may be thrown
Once an exception type that meets the specified exception type occurs during method execution, it will be thrown, and the subsequent code of the exception code will not be executed
- try catch really handles exceptions
Throws just throws the exception to the caller of the method and does not really handle the exception
- How to choose try catch or throws in development
- If the overridden method in the parent class does not handle exceptions in the throw mode, the child class cannot use throws; If the method overridden by the subclass has exceptions, you can only use try catch (multithreaded application)
- Several other methods are called successively in the executed methods. When these methods are executed in a progressive relationship, it is recommended to use throws for these methods and try catch for the executed methods
Override method exception thrown
The exception type thrown by the method overridden by the subclass is not greater than the exception type thrown by the method overridden by the parent class. The parent class does not throw exceptions, nor can the child class
Throw exception manually
throw new RuntimeException("The data you entered is illegal!");//Run time exceptions can be ignored throw new Exception("The data you entered is illegal!");//Contains compile time exceptions that must be handled. You can add throws to the method declaration to handle the corresponding exception object
How to customize exceptions
//1. Inherit from the existing Exception structure, RuntimeException, Exception public class MyException extends RuntimeException{ //2. Provide global constants serialVersionUID version serial number identification class static final long serialVersionUID = -7034897190745766939L; //3. Provide overload constructor public MyException() { } public MyException(String msg) { super(msg); } }