Java_ exception handling

Keywords: Java

1, Overview of exceptions

In the Java language, abnormal conditions occurring in program execution are called exceptions.

1. Anomaly classification

There are two types of abnormal times during the execution of Java programs:

  • Error: a serious problem that cannot be solved by the Java virtual machine. For example, JVM system internal errors, resource exhaustion and other serious situations (such as StackOverflowError and OOM). Generally, targeted code is not written.
  • Exception: other general problems caused by program errors or accidental external factors can be handled with targeted code. The best way to catch exceptions is during compilation, but some errors occur only at run time, so they are divided into compile time exceptions and run-time exceptions.

2. Compile time exception and runtime exception

(1) Compile time exception

  • A: IOCxception

    • a: FileNotFoundException
  • B: ClassNotFountException

(2) Runtime exception

  • NullPointerException
   // NullPointerException
   	@Test
   	public void test1() {
   		// int[] arr = null;
   		// System.out.println(arr[3]);
   
   		String str = "abc";
   		str = null;
   		System.out.println(str.charAt(0));
   	}
  • ArrayIndexOutOfBoundsException
  // ArrayIndexOutOfBoundsException
  	@Test
  	public void test2() {
  		// int[] arr = new int[10];
  		// System.out.println(arr[10]);
  
  		String str = "abc";
  		System.out.println(str.charAt(3));
  	}
  • ClassCastException
  // ClassCaseException
  	@Test
  	public void test3() {
  		 Object obj = new Date();
  		 String str = (String)obj;
  	}
  • NumberFormatException
  // NumberFormatException
  	@Test
  	public void test4() {
  		String str = "123";
  		str = "abc";
  		int num = Integer.parseInt(str);
  	}
  • InputMismatchException
  	// InputMismatchException
  	@Test
  	public void test5() {
  		Scanner scanner = new Scanner(System.in);
  		int score = scanner.nextInt();
  		System.out.println(score);
  
  		scanner.close();
  	}
  • ArithmeticException
  	// ArithmeticException
  	@Test
  	public void test6() {
  		int a = 10;
  		int b = 0;
  		System.out.println(a / b);
  	}

2, Exception handling

Exception handling: grab and throw model

Process 1: "throwing": once an exception occurs during the normal execution of the program, it will be born into an object corresponding to the exception class in the exception code. And throw this object. Once the object is thrown, the subsequent code is no longer executed.

Process 2: "catch": it can be understood as the exception handling method: 1. Try catch finally 2. Throws

The exception handling mechanism adopted by Java is to concentrate the exception handling program code together and separate it from the normal program code, making the program concise, elegant and easy to maintain.

Generation of exception objects: ① exception objects generated automatically by the system; ② manually generate an exception object and throw it

1. Exception handling mechanism I

(1)try-catch-finally

try{
 		//Possible exception codes
 }catch(Exception type 1 variable name 1){
 		//How to handle exceptions 1
 }catch(Exception type 2 variable name 2){
 		//How to handle exceptions 2
 }catch(Exception type 3 variable name 3){
 		//How to handle exceptions 3
 }
 ...
 finally{
 		//Code that must execute
 }

(2)try

The first step of catching exceptions is to use the try {...} statement block to select the scope of catching exceptions, and put the code block with possible exceptions in the try statement block.

(3)catch

In the catch statement block, it is the code block that handles the exception object. Each try statement block can be accompanied by one or more catch statements to handle different types of exception objects that may occur. Format: catch (exception type parameter name)

(4)finally

  • finally is optional
  • finally, what is declared is the code that must be executed. Even if there are exceptions in catch, return statements in try and return statements in catch.
  • Resources such as database connection, input / output stream and network programming Socket cannot be recycled automatically by the JVM. We need to release resources manually. At this time, the resource release needs to be declared in finally.

(5) Capture information about exception information

Like other objects, you can access the member variables of an exception object or call its methods.

  • getMessage(): get exception information and return string.
  • printStackTrace(): get the exception class name, exception information, and the location of the exception in the program, and return void.

(6) Explain

  • try is used to wrap the possible exception code. In case of an exception during execution, an object corresponding to the exception class will be generated. According to the type of this object, it will be matched in catch.
  • Once the exception object in the try matches a catch, it enters the catch for exception processing. Once the processing is completed, it jumps out of the current try catch structure (without writing finally). Continue with the following code.
  • If the exception type in catch has no child parent relationship, it doesn't matter who declares it on and who declares it under. If the exception type in catch satisfies the child parent relationship, the child class must be declared on the parent class. Otherwise, an error is reported
  • Common exception object handling methods: ① String getMessage() ② printStackTrace()
  • Variables declared in the try structure cannot be called after the try structure is created.
  • Try catch finally structures can be nested
  • Experience 1: use try catch finally 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. It is equivalent to using try catch finally to delay an exception that may occur during compilation until it occurs at run time.
  • Experience 2: in development, since runtime exceptions are common, we usually don't write try catch finally for runtime exceptions. For compile time exceptions, we say we must consider exception handling.

2. Exception handling mechanism II

throws + exception type

  • If a method (when the statement in is executed) may generate some kind of exception, but it is not sure how to handle this exception, the method should explicitly declare to throw an exception, indicating that the method will not handle these exceptions, but the caller of the method is responsible for handling them.
  • In the method declaration, the throw statement can be used to declare the list of exceptions thrown. The exception type after throws can be the exception type generated in the method or its parent class.
  • "throws + exception type" is written at the declaration of the method. Indicates the type of exception that may be thrown when this method is executed. Once an exception occurs during the execution of the method body, an exception class object will still be generated at the exception code. When this object meets the throw exception type, it will be thrown. Exception code and subsequent code will not be executed!
  • Try catch finally: the exception is really handled. Throws simply throws the exception to the caller of the method. The exception is not really handled.
public class ExceptionTest2 {
	
	public static void main(String[] args){
		try {
			method2();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		method3();
	}
	
	public static void method3(){
		try {
			method2();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void method2() throws IOException{
		method1();
	}

	
	public static void method1() throws FileNotFoundException,IOException{
		File file = new File("hello1.txt");
		FileInputStream fis = new FileInputStream(file);
		
		int data = fis.read();
		while(data != -1){
			System.out.print((char)data);
			data = fis.read();
		}
		
		fis.close();
		
		System.out.println("hahaha!");
	}
}

Principle of overriding method throwing exception: the exception type thrown by the method overridden by the subclass shall not be greater than the exception type thrown by the method overridden by the parent class

public class OverrideTest {
	
	public static void main(String[] args) {
		OverrideTest test = new OverrideTest();
		test.display(new SubClass());
	}
	
	public void display(SuperClass s){
		try {
			s.method();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
class SuperClass{
	
	public void method() throws IOException{
		
	}
}
class SubClass extends SuperClass{
	public void method()throws FileNotFoundException{
		
	}
}

How to choose whether to use try catch finally or throws in development?

  • If the overridden method in the parent class does not handle exceptions in the throw mode, the overridden method of the child class cannot use throws, which means that if there are exceptions in the overridden method of the child class, it must be handled in the try catch finally mode.
  • In the executed method a, several other methods are called successively, which are executed in a progressive relationship. We suggest that these methods be handled in the way of throws. For the executed method a, try catch finally can be considered.

3, Throw exception manually

Java exception class objects are automatically generated and thrown by the system when exceptions occur during program execution. They can also be manually created and thrown as needed.

  • First, the exception class object is generated, and then the throw operation is implemented through the throw statement (submitted to the Java runtime environment)
  • The exception that can be thrown must be an instance of Throwable or its subclass.
public class StudentTest {
	public static void main(String[] args) {
		try {
			Student s = new Student();
//		s.regist(1001);
			s.regist(-1001);
			System.out.println(s);
		} catch (Exception e) {
//			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}
}
class Student{
	private int id;
	
	public void regist(int id) throws Exception{
		if(id > 0){
			this.id = id;
		}else{
//			System.out.println("the data you entered is illegal!");
			//Throw exception manually
//			throw new RuntimeException("the data you entered is illegal!");
			throw new Exception("The data you entered is illegal!");
			
		}
	}

	@Override
	public String toString() {
		return "Student [id=" + id + "]";
	}
	
}

4, Custom exception class

  • Generally, user-defined exception classes are subclasses of RuntimeException.
  • Custom exception classes usually require writing several overloaded constructors.
  • A serialVersionUID is required for custom exceptions
  • Custom exceptions are thrown through throw.
  • The most important thing for custom exceptions is the name of the exception class. When an exception occurs, you can judge the exception type according to the name.
/*
 * How to customize exception classes?
 * 1.Inherited from the existing Exception structure: RuntimeException, Exception
 * 2.Provide global constant: serialVersionUID
 * 3.Provides overloaded constructors
 * 
 */
public class MyException extends RuntimeException{
	static final long serialVersionUID = -7034897193246939L;
	
	public MyException(){
		
	}
	
	public MyException(String msg){
		super(msg);
	}
}

Posted by chaser7016 on Tue, 05 Oct 2021 12:34:34 -0700