Exception handling (unfinished)

1, Exception overview and exception architecture

Syntax errors and logic errors in the development process are not exceptions

The abnormal events that occur during the execution of Java programs can be divided into two categories:
>Error: a serious problem that cannot be solved by the Java virtual machine. For example: JVM system internal error, resource
Depletion and other serious situations. For example, StackOverflowError and OOM. In general, targeted documents are not prepared
Code for processing. Examples are as follows:

​
​
/*
 * Error:
 * Java A serious problem that the virtual machine cannot solve. Such as: JVM system internal error, resource exhaustion and other serious situations. For example, StackOverflowError and OOM.
 * 
 * Generally, targeted code is not written for processing.
 * 
 * 
 */
public class ErrorTest {
	public static void main(String[] args) {
		//1. Stack overflow: java.lang.StackOverflowError
//		main(args);
		//2. Heap overflow: java.lang.OutOfMemoryError 
		Integer[] arr = new Integer[1024*1024*1024];
		
	}
}

​

​

>Exception: other general problems caused by programming errors or accidental external factors can make
Handle with targeted code. For example:
>Null pointer access
>An attempt was made to read a file that does not exist
>Network connection interrupted
>Array subscript out of bounds

It is ideal to catch errors during compilation, but some errors occur only at run time.
For example, the divisor is 0, the array subscript is out of bounds, etc
>Classification: compile time exception and run time exception
Runtime exception: generally refers to the logic error during programming. It is an exception that programmers should actively avoid. The java.lang.RuntimeException class and its subclasses are runtime exceptions. This kind of exception can not be handled because it is very common. If it is fully handled, it may affect the readability and running efficiency of the program.

2, Common anomalies

1, Exception architecture
  java.lang.Throwable
          |----- java.lang.Error: generally, targeted code is not written for processing.
          |----- java.lang.Exception: you can handle exceptions
              |------ Compile time exception (checked)
                      |-----IOException
                          |-----FileNotFoundException
                      |-----ClassNotFoundException
              |------ Runtime exception (unchecked,RuntimeException)
                      |-----NullPointerException
                      |-----ArrayIndexOutOfBoundsException
                      |-----ClassCastException
                      |-----NumberFormatException
                      |-----InputMismatchException
                      |-----ArithmeticException
   Interview question: what are the common exceptions? Examples

3, Exception handling mechanism 1: try catch finally

4, Exception handling mechanism 2: throws

5, Throw exception manually

6, User defined exception class

2.

import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.Scanner;

import org.junit.Test;

/*
 * 1, Exception architecture
 * 
 * java.lang.Throwable
 * 		|-----java.lang.Error:Generally, targeted code is not written for processing.
 * 		|-----java.lang.Exception:You can handle exceptions
 * 			|------Compile time exception (checked)
 * 					|-----IOException
 * 						|-----FileNotFoundException
 * 					|-----ClassNotFoundException
 * 			|------Runtime exception (unchecked,RuntimeException)
 * 					|-----NullPointerException
 * 					|-----ArrayIndexOutOfBoundsException
 * 					|-----ClassCastException
 * 					|-----NumberFormatException
 * 					|-----InputMismatchException
 * 					|-----ArithmeticException
 * 
 * 
 * 
 * Interview question: what are the common exceptions? Examples
 */
public class ExceptionTest {
	
	//******************The following are compile time exceptions***************************
	@Test
	public void test7(){
//		File file = new File("hello.txt");
//		FileInputStream fis = new FileInputStream(file);
//		
//		int data = fis.read();
//		while(data != -1){
//			System.out.print((char)data);
//			data = fis.read();
//		}
//		
//		fis.close();
		
	}
	
	//******************The following are runtime exceptions***************************
	//ArithmeticException
	@Test
	public void test6(){
		int a = 10;
		int b = 0;
		System.out.println(a / b);
	}
	
	//InputMismatchException
	@Test
	public void test5(){
		Scanner scanner = new Scanner(System.in);
		int score = scanner.nextInt();
		System.out.println(score);
		
		scanner.close();
	}
	
	//NumberFormatException
	@Test
	public void test4(){
		
		String str = "123";
		str = "abc";
		int num = Integer.parseInt(str);
		
		
		
	}
	
	//ClassCastException
	@Test
	public void test3(){
		Object obj = new Date();
		String str = (String)obj;
	}
	
	//IndexOutOfBoundsException
	@Test
	public void test2(){
		//ArrayIndexOutOfBoundsException
//		int[] arr = new int[10];
//		System.out.println(arr[10]);
		//StringIndexOutOfBoundsException
		String str = "abc";
		System.out.println(str.charAt(3));
	}
	
	//NullPointerException
	@Test
	public void test1(){
		
//		int[] arr = null;
//		System.out.println(arr[3]);
		
		String str = "abc";
		str = null;
		System.out.println(str.charAt(0));
		
	}
	
	
}

 3.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.junit.Test;

/*
 * 1, Exception handling: grab and throw model
 * 
 * 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 object.
 *           Once the object is thrown, the subsequent code is no longer executed.
 * 		
 * 		Generation of abnormal objects: ① abnormal objects automatically generated by the system
 * 					 ② Manually generate an exception object and throw it
 * 
 * Process 2: "catch": it can be understood as the exception handling method: ① try catch finally ② throws
 * 
 * 
 * 2, Use of 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
 * }
 * 
 * explain:
 * 1. finally Is optional.
 * 2. 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 this object
 *    To match the type in catch
 * 3. Once the exception object in the try matches a catch, it will enter the catch for exception processing. Once the processing is completed, it will jump out of the current catch
 *    try-catch Structure (without writing finally). Continue to execute the following code
 * 4. catch If the exception type in has no child parent relationship, it doesn't matter who declares it on and who declares it under.
 *    catch If the exception type in satisfies the child parent relationship, the child class must be declared on the parent class. Otherwise, an error is reported
 * 5. Common exception object handling methods: ① string getmessage() ② printStackTrace()
 * 6. Variables declared in the try structure cannot be called after the try structure is created
 * 7. 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.
 */
public class ExceptionTest1 {
	
	
	@Test
	public void test2(){
		try{
			File file = new File("hello.txt");
			FileInputStream fis = new FileInputStream(file);
			
			int data = fis.read();
			while(data != -1){
				System.out.print((char)data);
				data = fis.read();
			}
			
			fis.close();
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
	@Test
	public void test1(){
		
		String str = "123";
		str = "abc";
		int num = 0;
		try{
			num = Integer.parseInt(str);
			
			System.out.println("hello-----1");
		}catch(NumberFormatException e){
//			System.out.println("numerical conversion exception occurs, don't worry...);
			//String getMessage():
//			System.out.println(e.getMessage());
			//printStackTrace():
			e.printStackTrace();
		}catch(NullPointerException e){
			System.out.println("There is a null pointer exception. Don't worry....");
		}catch(Exception e){
			System.out.println("There's something unusual. Don't worry....");
			
		}
		System.out.println(num);
		
		System.out.println("hello-----2");
	}
	
}

Keywords: Java

Added by Percadan on Tue, 28 Sep 2021 07:33:23 +0300