Anomaly classification
1, Error
Serious problems that cannot be solved by the Java virtual machine.
If the JVM has an internal error, the resource is exhausted. StackoverflowError,OOM
Generally, targeted code is not written to solve such errors. It can only be solved by modifying the code.
2, Exception
General problems caused by programming errors or external factors
Although exceptions refer to error and Exception, exceptions in Exception handling usually refer to Exception.
For example, in int type input, input character type content, null pointer access, array corner mark out of bounds, and read nonexistent files
Write targeted code to solve such errors
3, Exception architecture
4, Exception handling mechanism (key)
Exception handling
* Process 1: "throwing": 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 throw this exception * Once thrown, subsequent code is no longer executed * * Generation of exception objects:① System automatically generated exception * ② Manually generate exception objects and throw * * Process: "grasping": can be understood as the exception handling method:①try-catch-finally ② throws + Exception type
Process 1: throw
"Throwing": 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 throw this exception. Once thrown, the subsequent code will not be executed.
Generation of exception objects:
① System automatically generated exception
Process 2: "grasping"
Processing method 1 - try - catch - finally
//try - catch - finally structure import org.junit.Test; public class MyTestForLearn { @Test public void ExceptionTest() { //try is used to wrap up the statements with possible exceptions. In the process of execution, once an exception occurs, a corresponding exception class object will be generated. According to the type of this object, it will be matched in the catch try { int array1[] = new int[10]; array1[10] = 10; } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace();//Print details System.out.println(e.getMessage());//Output: "Index 10 out of bounds for length 10" System.out.println("Null pointer exception"); } //Once the exception in the try matches a catch. Enter the catch for exception handling. Once the processing is completed, jump out of the current try - catch and continue to execute the subsequent structure System.out.println("Jump out try - catch - finally The statement after the structure continues to execute"); } }
output
java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10 at project1.MyTestForLearn.ExceptionTest(MyTestForLearn.java:11) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:567) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306) at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63) at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329) at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293) at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306) at org.junit.runners.ParentRunner.run(ParentRunner.java:413) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:93) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210) Index 10 out of bounds for length 10 Null pointer exception Jump out try - catch - finally The statement after the structure continues to execute
Description of finally
Finally is not necessary in the try - catch - finally structure, but it will be executed once it occurs. Even if there are exceptions in catch, or there are return statements in try and catch. The code is described below
Example 1 - no finally
public int ExceptionTest() { try { return 1; } catch (Exception e) { System.out.println(e.getMessage());//Output: "Index 10 out of bounds for length 10" System.out.println("abnormal"); return 3; } //Compilation failed: Unreachable code return 3; }
Example 2 - add finally
public class MyTestForLearn { public static void main(String[] args) { System.out.println(ExceptionTest()); } public static int ExceptionTest() { try { return 1; } catch (Exception e) { System.out.println(e.getMessage());//Output: "Index 10 out of bounds for length 10" System.out.println("abnormal"); return 2; }finally { return 3; } } } Output: 3
finally Application of:Database link, input / output stream, network programming Scocket Other resources JVM It can't be recycled automatically, We need to release resources manually.The resource release at this time needs to be declared in finally Yes.
For exception types in catch, if there is a child parent relationship, the child class must be declared first
public void ExceptionTest2() { try { int a[] = new int[10]; } catch (Exception e) { e.printStackTrace(); }catch ( NullPointerException e) { } } Here because Exception yes NullPointerException Compilation failed because of the parent type of: Unreachable catch block for NullPointerException. It is already handled by the catch block for Exception
Common exception object handling methods:
① String type e.getMessage()
② e.printStackTrace() / / more commonly used
@Test public void ExceptionTest1() { try { int a[] = new int[10]; System.out.println(a[10]); } catch (Exception e) { System.out.println(e.getMessage());//Output: "Index 10 out of bounds for length 10" e.printStackTrace(); } }
Output:
Index 10 out of bounds for length 10 java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10 at project1.MyTestForLearn.ExceptionTest1(MyTestForLearn.java:29) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:567) ..........
Other considerations about try - catch - finally
The variables defined in the try structure cannot be called after the try structure
The try - catch structure can be nested
@Test public void test2() { FileInputStream fis = null; try { File file = new File("hello.tect"); fis = new FileInputStream(file); int data = fis.read(); while(data != -1) { System.out.println((char)data); data = fis.read(); } // fis.close(); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); // e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ //Use nesting try {if(fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); } } }
Processing method 2 - throws + exception type
usage method
//The throws + exception type is written at the declaration of the method. Indicates that this method execution is an exception type that may be thrown public static void method1() throws FileNotFoundException,IOException{ File file = new File("hello.text"); //Once a method is called and an exception occurs, an exception class object will still be generated at the code exception. When this object meets the throw exception type, it will be thrown. Exception code and subsequent code will not be executed FileInputStream fis = new FileInputStream(file); int data = fis.read(); while(data != -1) { System.out.println((char)data); data = fis.read(); } fis.close(); }
The exception type in throws. The method exception type thrown by the method overridden by the subclass cannot be greater than that of the method in the parent class
/* * The method exception type thrown by the method overridden by the subclass cannot be greater than that of the method in the parent class */ class SubClass extends SuperClass{ public static void method1() throws FileNotFoundException{ } //Exception Exception is not compatible with throws clause in SuperClass.method1() //Cannot be larger than the parent exception type // public static void method1() throws Exception{ // // } } //Declare a parent class class SuperClass{ public static void method1() throws IOException{ File file = new File("hello.text"); FileInputStream fis = new FileInputStream(file); int data = fis.read(); while(data != -1) { System.out.println((char)data); data = fis.read(); } fis.close(); } }
② Manually generate exception objects and throw custom exception classes
Custom exception class EcDef
public class EcDef extends Exception{ //1, Defines the global constant serialVersionUID that uniquely identifies an exception type static final long serialVersionUID = -33875169229948L; //2, Define a parameterless constructor public EcDef(){} //3, Constructor with parameters, calling constructor of parent exception type public EcDef(String msg){ super(msg); } }
EcmDef class
/* * Receive two parameters from the command line, test, right-click - > run as - > Run configurations * * */ public class EcmDef { public static void main(String[] args) { try { int int1 = Integer.parseInt(args[0]); int int2 = Integer.parseInt(args[1]); int result = ecm(int1 ,int2); System.out.println(result); } catch (NumberFormatException e) { // TODO Auto-generated catch block System.out.println("Inconsistent data type");; } catch (ArrayIndexOutOfBoundsException e ) { System.out.println("Missing command line argument"); } catch (ArithmeticException e) { System.out.println("Divide by 0"); } catch (EcDef e) { //"Grab" custom exception System.out.println(e.getMessage()); } } //Calculate the division of two numbers and throw a custom exception public static int ecm(int i,int j) throws EcDef { if(i < 0 || j < 0) { throw new EcDef("Numerator or denominator is negative"); } return i/j; } }
The exception thrown by method A is solved by method B calling this exception method. Method B can also continue to throw this exception upward, but up to the main method, you must use the try - catch - finally structure to solve the exception.
try - catch - finally : Really handled the exception throws The method only throws the exception to the caller of the method, and does not handle the exception
Summary: how to determine which of the two exception handling methods is selected?
① The method in the parent class does not use throws, and the subclass cannot use throws when overriding, which means that if the subclass has exceptions, catch must be used
② Several other methods are called successively in the executed methods, which are progressive. It is suggested that these methods be processed in the way of throws. The method of execution can be handled in catch mode