Exception class handling

Posted by MemphiS on Mon, 08 Nov 2021 13:55:22 +0100

1, System interface of exception handling class

1. It is normal for the program to be abnormal [just like people will get sick]
2. Exception class Throwable [class] top level exception class in Java
3.Throwable [class] has two subclasses: 1. Error   2. Exception
    Error is an unexpected exception in the running of java programs. After this exception occurs, it will directly lead to the unhandled or unrecoverable situation of the JVM. Therefore, such exceptions cannot be captured, such as OutOfMemoryError, NoClassDefFoundError, etc. [cancer]
4. Exceptions are divided into runtime exceptions and non runtime exceptions
     Runtime exceptions -- non checking exceptions can be ignored in code writing (such as ArrayIndexOutOfBoundsException). Such exceptions can be avoided through specifications during code writing or use.
     Non runtime exceptions -- checking exceptions must be caught using try catch (such as IOException exception) when writing code.

  2, Principle of java exception handling

1. Exceptions can be handled by yourself
        Handle exceptions through the try catch code block.
      The java code with possible exceptions is wrapped with the "try {code with possible exceptions} catch (exception to catch) {exception handling method}" block. If an exception occurs, try {} will catch the exception, terminate the operation of the code, and hand the caught exception to catch() {} to handle the exception.
     Try catch code block
     Format:
    try{
         Code for possible exceptions
       } Catch (exception type to catch){
         Exception handling method
     }
            1.try{}-- catch possible exceptions
             2.catch (/ / exception to be captured) {/ / exception handling method} --- capture and handle exceptions
               "()" after catch is generally defined as a specific exception type.
               When the specific exception type is ambiguous, you can use Exception/Throwable
               catch's {} - specific exception handling process. It is often to print the stack to the console, check the specific situation, and modify the program to avoid it
             3. A try {} can be followed by multiple catches (exceptions to be captured) {exception handling method}. The types of exceptions to be captured in multiple catches need to be arranged in the order from small to large.
             4. [finally {}] - appears after "{}" in catch. It can be written or not.
                                      Actions to be performed whether there are exceptions or not.
                  When there is certain code to be executed, it is written to finally.
For example:

package com.wangxing.test1;
public class testClass {
	public void method(int size){
		int arr[]=new int[size];
		System.out.println(arr.length);
	}
}
package com.wangxing.test1;
import java.util.Scanner;

public class mainTest {
	public static void main(String[] args) {
			Scanner scn=new Scanner(System.in);
			System.out.println("Please enter the size of the array you want to create");
			String sg=scn.next();
			int size=Integer.parseInt(sg);
			testClass tc=new testClass();
			tc.method(size);
	}
}

When the size of the array is negative, an error will be reported

Solution:

package com.wangxing.test1;
import java.util.Scanner;

public class mainTest {
	public static void main(String[] args) {
		try{
			Scanner scn=new Scanner(System.in);
			System.out.println("Please enter the size of the array you want to create");
			String sg=scn.next();
			int size=Integer.parseInt(sg);
			testClass tc=new testClass();
			tc.method(size);
		}catch(Exception e){
			Scanner scn=new Scanner(System.in);
			System.out.println("Please enter the size of the array you want to create");
			String sg=scn.next();
			int size=Integer.parseInt(sg);
			if(size>0){
				size=size;
			}else{
				size=0-size;
			}
			testClass tc=new testClass();
			tc.method(size);
		}finally{
			System.out.println("Execute whether there are exceptions or not"); 
		}
	}
}

Interview question: does return in try catch execute before or after finally?
         finally statement is executed after the return statement is executed and before the return statement is returned.
public  static String  getString(){
         String   he = "hello";
        try{
            he="hello";
        }catch(Exception e){
            e.printStackTrace();
        }finally{
             System.out.println("execute whether there are exceptions or not");  
            he="hello,lisi";
        }
        return he;  
    } 

two   Exceptions are not handled by themselves
         If an exception occurs, java will create an object (instance) specific exception object according to the exception class described by the problem, and then throw the object to the upper level [whoever invokes it is the upper level],
     Specific steps:
     Method specify the exception -- "main method --" jvm virtual machine -- "print the location and reason of the exception on the console
     Throws -- declare that the method throws an exception to the upper level [whoever invokes it is the upper level]
For example:

package com.wangxing.test2;

public class testClass {
	public int getint()throws Exception{
		int a=10;
		int b=0;
		int c=a/b;
		return c;
	}
}
package com.wangxing.test2;

public class testMain {
	public static void main(String[] args)throws Exception{
		testClass tc =new testClass();
		int res= tc.getint();
		System.out.print("res=="+res);
	}
}

1. Throw the error in testClass to the main method, which is handed over to the java virtual machine and then to the console

  3.throw keyword and custom exception
          Simple custom exception -- write a new class, inherit Throwable/Exception/RumtimeException, and access the construction method of the parent class in the construction
Create a custom exception

package com.wangxing.test3;

public class myException extends Exception{
	public myException(String info){
		super();
		System.out.println(info);
	}
}
package com.wangxing.test3;

public class testClass {
	public testClass(int size) throws myException{
		if(size>0){
			size=size;
			int arr[]=new int[size];
			System.out.println(arr.length);
		}else{
			throw new myException("Array size cannot be negative");
		}
		
	}
}
package com.wangxing.test3;

public class main {
	 public static void main(String[] args){
		try{
			testClass tc=new testClass(-5);
		}catch(myException e){
			e.printStackTrace();
		}
	}	
}

  To sum up: 1. If there is an exception, try{}catch() {}. If you don't want to try{}catch() {}, declare the method throws exception.
     2. When there are no special requirements, we print stack exceptions to view the specific exceptions and locations of the program for easy modification.
     3. We can't easily define exceptions ourselves, because the exception types provided by java are enough.

4. Common runtime exceptions in Java
     1.NullPointerException - null pointer reference exception
     2.ClassCastException - type cast exception.
     3.IllegalArgumentException - pass illegal parameter exception.
     4.ArithmeticException - arithmetic operation exception
     5.ArrayStoreException - store an object exception incompatible with the declared type into the array
     6.IndexOutOfBoundsException - subscript out of bounds exception
     7.NegativeArraySizeException - create an array error exception with a negative size
     8.NumberFormatException - number format exception
     9.SecurityException - Security Exception
     10. Unsupported operationexception - unsupported operation exception

Topics: Java Back-end