9, Exception handling

  This article is based on Video Science, and the sources are as follows:

Tutorial source:

Java basic to advanced_ Zero foundation self-study Java – shangsilicon Valley – song Hongkang
Tutorial video address:

 Java basic to advanced_ Zero foundation self-study Java -- still Silicon Valley -- song Hongkang_ Beep beep beep_ bilibilihttps://www.bilibili.com/video/BV1ny4y1Y7CW

catalogue

1. The first thing to note about the use of local internal classes

2. Exception overview

3. Classification of anomalies

4. Examples of common anomalies

5. Overview of exception handling methods

6. Exception handling: try catch mode

7.finally use

8. Different handling methods for compile time exceptions and runtime exceptions

9. Exception handling: throws mode

10. Override the rule of method exception throwing

11. How to choose which method to handle exceptions in development

12. Manually throw exception object

13. How to customize exceptions

14. Basic use of exception handling exercises

15. Comprehensive use of exception handling exercises

16. Summary of exception handling section

1. The first thing to note about the use of local internal classes

package com.atshangguigu.java;
/*((specified)
 * In the methods of the local inner class (for example: show()), if you want to call the local variable (such as num) in the method declared by the local variable inner class (for example: method)
 *This local variable is required to be declared final
 *jdk7 And previous versions: this local variable is required to be explicitly declared final
 *jdk8 And later versions: the declaration of final can be omitted

 */
public class InnerClassTest {
	public void onCreate()
	{
		button.setOnClickListener(new View.OnClickListener(){
			public void onClick()
			{
				System.out.println("hello");
			}
		});
	}
	//local variable
	int num = 10;
	class AA
	{
		public void show()
		{
			System.out.println(num);
		}
	}
}

2. Exception overview

  • Exception: in the Java language, abnormal conditions during program execution are called "exceptions" (syntax 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 : Java A serious problem that the virtual machine cannot solve. For example: JVM System internal error, resource exhaustion and other serious conditions. For example: StackOverflowError and OOM . Generally, targeted code is not written for processing. (serious problem)
    Exception: Other general problems caused by programming errors or accidental external factors can be handled 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
package com.atshangguigu.java;
/*
 * Java Problems that cannot be solved by virtual machines
 */
public class ErrorTest {
public static void main(String[] args) {
	//A.Error
	
	//1. Stack overflow: java.lang.StackOverflowError
	//main(args);
	//2. Heap overflow: java.lang.OutOfMemoryError: Java heap space
	//Integer[] arr = new Integer[1024 * 1024 * 1024];
	
	//B. Exception (exception in a narrow sense)
	
}
}

3. Classification of anomalies

  • For these errors, there are generally two solutions: one is to terminate the operation of the program in case of an error. Another method is that programmers consider error detection, error message prompt and error handling when writing programs.
    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
package com.atshangguigu.java;
/*
 * 1, Abnormal 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)  
 * 				|*****NullPointerException(Null pointer exception)
 * 				|*****ArrayIndexOutOfBoundsException(Angle mark (out of bounds)
 * 				|*****ClassCastException
 * 				|*****NumberFormatException
 * 				|*****InputMismatchException
 * 				|*****ArithmeticException(Arithmetic exception)
 * 
 * Interview question: what are the common exceptions? Please give an example
 */
public class ExceptionTest {

}

4. Examples of common anomalies

package com.atshangguigu.java;

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

import org.junit.Test;

/*
 * 1, Abnormal 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)  
 * 				|*****NullPointerException(Null pointer exception)
 * 				|*****ArrayIndexOutOfBoundsException(Angle mark (out of bounds)
 * 				|*****ClassCastException
 * 				|*****NumberFormatException
 * 				|*****InputMismatchException(s Input exception)
 * 				|*****ArithmeticException(Arithmetic exception)
 * 
 * Interview question: what are the common exceptions? Please give an example
 */
public class ExceptionTest {
	/********************************(The following are exceptions during compilation)***************************************************/
	@Test
	public void test07()
	{
		File file = new File("Hello.txt");
		FileInputStream fis = new FileInputStream(file);
		int data = fis.read();
		while(data != -1)
		{
			System.out.println((char)data);
			data = fis.read();
		}
		fis.close();
	}
	/********************************(The following is the runtime exception)******************************************/
	//6. Arithmeticexception (arithmetic exception)
	@Test
	public void test06()
	{
		int a = 10;
		int b = 0;
		System.out.println(a/b);
	}
	//5.InputMismatchException
	@Test
	public void test5()
	{
		Scanner scanner = new Scanner(System.in);
		int score = scanner.nextInt();
		System.out.println(score);
		scanner.close();
	}
	//4.NmberFormatException
	@Test
	public void test4()
	{
		String str = "123";
		str = "abc";
		int num = Integer.parseInt(str);
	}
	//3.ClassCastException
	@Test
	public void test3()
	{
		Object obj = new Date();
		String Str = (String)obj;
	}
	//2.IndexOutOfBoundsException
	@Test
	public void test2()
	{
		//(1)ArrayIndexOutOfBoundsException
//		int[] arr = new int[10];
//		System.out.println(arr[10]);
		//(2)StringIndexOutOfBoundsException
		String str = "abc";
		System.out.println(str.charAt(3));
	}
	//1.NullPointerException
	@Test
	public void test1()
	{
		//(1)
//		int[] arr = null;
//		System.out.println(arr[15]);
		//(2)
		String str = "abc";
		str = null;
		System.out.println(str.charAt(2));
	}		
	
}

5. Overview of exception handling methods

  • When writing a program, it is often necessary to add detection code where errors may occur. For example, when performing x/y operation, it is necessary to detect that the denominator is 0, the data is empty, and the input is not data but characters. Too many if else branches will lead to the code lengthening, bloated and poor readability of the program. Therefore, the exception handling mechanism is adopted.
  • Java exception handling
    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.
    Mode 1: try-catch-finally       : I solved the wolf myself
    Mode 2: throws + Exception type: call people to beat wolves --- if you can't do it, report it to your superiors and call people

    package com.atshangguigu.java;
    /*
     * Exception handling: grab and throw model
     * Process 1: "throw" -- once an exception occurs during the execution of the program, an object corresponding to the exception class will appear at the exception code
     * 				And throw this object
     * 				Once the object is thrown, the subsequent code will not be executed
     * Process 2: "catch" -- exception handling methods: (1) try catch finally (2) throws
     */
    public class ExceptionTest1 {
    
    }
    

6. Exception handling: try catch mode

package com.atshangguigu.java;
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: "throw" -- once an exception occurs during the execution of the program, an object corresponding to the exception class will appear at the exception code
 * 				And throw this object
 * 				Once the object is thrown, the subsequent code will not be executed
 * Process 2: "catch" -- exception handling methods: (1) try catch finally (2) throws
 * 
 * 2, Use of try - catch - finally
 * try
 * {
 * 		Possible exception codes
 * }
 * throw(Exception type 1 (variable name 1)
 * {
 * 		How to handle exceptions 1
 * }
 * throw(Exception type 2 (variable name 2)
 * {
 * 		How to handle exceptions 2
 * }
 * throw(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 code with possible exceptions. Once an exception occurs during execution, an object corresponding to the exception class will be generated according to the type of the object
 *   Match 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 structure (without writing)
 *   final In this case, continue to execute the subsequent code
 * 4.catch If there is no child parent relationship, it doesn't matter who declares on and who declares below
 * 					    If the relationship between child and parent is satisfied, the parent must be declared above the parent. Otherwise, an error will be reported
 * 5.Common exception handling methods: (1)String getMessage() (2)printStackTrace() -- more commonly used
 * 6.Variables declared in the try structure cannot be called after the try structure
 * 7.Experience: using try - catch - finally to handle compile time exceptions means that the program will no longer report errors when compiling, but it may still report errors when running/
 *       It is equivalent to converting an exception that may occur during compilation to an exception that occurs during runtime
 */
public class ExceptionTest1 {
	@Test
	public void test07()
	{
		try{
		File file = new File("Hello.txt");
		FileInputStream fis = new FileInputStream(file);
		int data = fis.read();
		while(data != -1)
		{
			System.out.println((char)data);
			data = fis.read();
		}
		fis.close();
	}
	catch(FileNotFoundException e)
		{
		e.printStackTrace();
		}
		catch(IOException e)
		{
		e.printStackTrace();
		}
	}
	@Test
	public void test4()
	{
		String str = "123";
		str = "abc";
		try{
			System.out.println("hello --------0");
			int num = Integer.parseInt(str);	
			System.out.println("hello --------1");
		}
		catch(NullPointerException e)//You can't take the wrong medicine. If you take the wrong medicine, you won't cure the disease!!!
		{
			System.out.println("Null pointer exception occurred,Don't worry");
		}
		catch(NumberFormatException e)//You can't take the wrong medicine. If you take the wrong medicine, you won't cure the disease!!!
		{
			//System.out.println("don't worry if there is abnormal value conversion");
			System.out.println(e.getMessage());
			e.printStackTrace();//Include e.getMessage()
		}
		catch(Exception e)//You can't take the wrong medicine. If you take the wrong medicine, you won't cure the disease!!!
		{
			System.out.println("Something's wrong,Don't worry");
		}
		System.out.println("hello --------2");
	}
}

7.finally use

  • Check - right click-
package com.atshangguigu.java;

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

import org.junit.Test;

/*
 * try-catch-finally Use of finally in:
 * 1.finally Is optional, according to the actual situation
 * 2.finally The code declared in is the code that must be executed. Even if an exception occurs in catch, there is a return statement in try and a return statement in catch
 * 3.The JVM cannot automatically recycle resources such as database connection input / output stream network programming Socket. We need to release resources manually and put them in finally
 * 4.try-catch-finally Structures can be nested
 */
public class FinallyTest {
	@Test
	public void test2()
	{
		FileInputStream fis = null;
		try {
			File file = new File("Hello.txt");
			fis = new FileInputStream(file);
			int data = fis.read();
			while(data != -1)
			{
				System.out.println((char)data);
				data = fis.read();
			}
			fis.close();
		} catch (FileNotFoundException e) {			
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(fis != null)
				fis.close();
			}
			catch (IOException e) 
			{
				e.printStackTrace();
			}
		}
	}
	
	@Test
	public void testMethod()
	{
		int num = method();
		System.out.println(num);
	}
	public int method()
	{
		try
		{
			int[] arr = new int[10];
			System.out.println(arr[10]);
			return 10;
		}
		catch(ArrayIndexOutOfBoundsException e)
		{
			e.printStackTrace();
			return 5;
		}
		finally 
		{
			System.out.println("I'll have a bucket of Master Kang in the evening");
		}
	}
	@Test
	public void test1()
	{
		try
		{
			int a = 10;
			int b = 0;
			System.out.println(a/b);
		}
		catch(ArithmeticException e)
		{
			e.printStackTrace();
			int[] arr = new int[10];
			System.out.println(arr[10]);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		//System.out.println("Xiao Yang, Xiao Yang, kaile");
		finally
		{
			System.out.println("Master Kang is a good teacher");
		}
	}
}

8. Different handling methods for compile time exceptions and runtime exceptions

  • New experience: in development, since runtime exceptions are common, we usually do not write try - catch - finally for runtime exceptions. However, for compile time exceptions, we must consider exception handling
package com.atshangguigu.java;

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

import org.junit.Test;

/*
 * try-catch-finally Use of finally in:
 * 1.finally Is optional, according to the actual situation
 * 2.finally The code declared in is the code that must be executed. Even if an exception occurs in catch, there is a return statement in try and a return statement in catch
 * 3.The JVM cannot automatically recycle resources such as database connection input / output stream network programming Socket. We need to release resources manually and put them in finally
 * 4.try-catch-finally Structures can be nested
 */
public class FinallyTest {
	@Test
	public void test2()
	{
		FileInputStream fis = null;
		try {
			File file = new File("Hello.txt");
			fis = new FileInputStream(file);
			int data = fis.read();
			while(data != -1)
			{
				System.out.println((char)data);
				data = fis.read();
			}
			fis.close();
		} catch (FileNotFoundException e) {			
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(fis != null)//Cannot comment
				fis.close();
			}
			catch (IOException e) 
			{
				e.printStackTrace();
			}
		}
	}
	
	@Test
	public void testMethod()
	{
		int num = method();
		System.out.println(num);
	}
	public int method()
	{
		try
		{
			int[] arr = new int[10];
			System.out.println(arr[10]);
			return 10;
		}
		catch(ArrayIndexOutOfBoundsException e)
		{
			e.printStackTrace();
			return 5;
		}
		finally 
		{
			System.out.println("I'll have a bucket of Master Kang in the evening");
		}
	}
	@Test
	public void test1()
	{
		try
		{
			int a = 10;
			int b = 0;
			System.out.println(a/b);
		}
		catch(ArithmeticException e)
		{
			e.printStackTrace();
			int[] arr = new int[10];
			System.out.println(arr[10]);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		//System.out.println("Xiao Yang, Xiao Yang, kaile");
		finally
		{
			System.out.println("Master Kang is a good teacher");
		}
	}
}

9. Exception handling: throws mode

package com.atshangguigu.java;

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

/*
 * Exception handling method 2: throws + exception handling method
 * 1. "throws + Exception type "is written in the declaration of the method, indicating the exception type that may be thrown when the method is executed
 * 	  Once an exception occurs when the method body is executed, an exception class object will still be generated at the exception code. When this object meets the exception type after throws
 *   Will be thrown, and the code behind the exception code will not continue to execute
 * 2.Experience: try catch finally: the exception is really handled
 *       throws The method knowledge throws the exception to the caller of the method, and does not really handle the exception
 * 
 */
public class ExceptionTest2 {
	public static void main(String[] args) {
		try{//Errors can always be thrown up, but the main method cannot throw data
			method2();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		method3();
	}
	public static void method2() throws IOException
	{
		method1();
	}
	public static void method3()
	{
		try
		{
			method2();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
public static void method1()
throws FileNotFoundException,IOException{
	File file = new File("Hello.txt");
	FileInputStream fis = new FileInputStream(file);
	int data = fis.read();
	while(data != -1)
	{
		System.out.println((char)data);
		data = fis.read();
	}
	fis.close();
	System.out.println("Ha ha ha ha ha ha");
}
}

10. Override the rule of method exception throwing

11. How to choose which method to handle exceptions in development

package com.atshangguigu.java1;
import java.io.FileNotFoundException;
import java.io.IOException;

/*
 * One of the rules for method overrides:
 * The exception type thrown by the method overridden by the subclass shall not be greater than the exception type overridden by the parent class
 * 
 * Follow the previous section:
 * 3.How to choose try catch finally or throw in development?
 * 	3.1 If the overridden method in the parent class does not handle exceptions in the throw mode, the child class can not handle exceptions with throws
 * 	    This means that if there is an exception in the method overridden by the subclass, it must be handled in a try catch finally manner - as mentioned in the following multithreading
 *    For example, in the main function, three progressive functions are written. It is best to use throws for exception handling, and finally try catch as a whole
 *  3.2 In the executed method A, several other methods are called successively. Several methods are executed in A progressive relationship. We suggest using the throw method
 *  	The executed method A can consider using the try catch finally method
 * 
 */
public class OverrideTest {
	public static void main(String[] args) {
		OverrideTest override = new OverrideTest();
		override.display(new SubClass());//Carry out polymorphism and call the function methods of subclasses
	}
	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//The method has been overridden and can only be exceptions smaller than the parent class
	{
		
	}
}

12. Manually throw exception object

  • [in the process of throwing exceptions] about the generation of exception objects: (1) the system automatically generates exception objects (2) manually generates an exception object and throws it
package com.atshangguigu.java1;

public class StudentTest {
public static void main(String[] args) {
	try {
		Student s = new Student();
		s.regist(-1000);
		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");
			//Manually throw an exception object
			//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 + "]";
	}
	
}

13. How to customize exceptions

package com.atshangguigu.java1;
/*
 * How to customize exception classes?
 * 1.Inherit the existing exception structure: RuntimeException Exception
 * 2.Provide a global constant: static final long serialVersionUID = -7034897190745766936L;
 *   It is equivalent to customizing a corresponding serial number
 * 3.Provides overloaded constructors
 */
public class MyException extends RuntimeException{

	static final long serialVersionUID = -7034897190745766936L;
	public MyException()
	{
		
	}
	public MyException(String msg)
	{
		super(msg);
	}
}

14. Basic use of exception handling exercises

package com.atshangguigu.java1;

public class ReturnExceptionDemo {

	static void methodA() {
		try {
			System.out.println("Entry method A");//1
			throw new RuntimeException("Manufacturing exception");//3
		} finally {
			System.out.println("use A Methodical finally");//2
		}
	}

	static void methodB() {
		try {
			System.out.println("Entry method B");//a
			return;//c
		} finally {
			System.out.println("call B Methodical finally");//b
		}
	}

	public static void main(String[] args) {
		try {
			methodA();
		} catch (Exception e) {
			System.out.println(e.getMessage());//Corresponding to 3 above
		}
		methodB();
	}
}
package com.atshangguigu.java1;

public class StudentTest {
public static void main(String[] args) {
	try {
		Student s = new Student();
		s.regist(-1000);
		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");
			//Manually throw an exception object
			//throw new RuntimeException("the data you entered is illegal");
			throw new MyException("???");
		}
	}
	@Override
	public String toString() {
		return "Student [id=" + id + "]";
	}
	
}

15. Comprehensive use of exception handling exercises

package com.atshangguigu.java2;

/*
 * Write the application program EcmDef.java to receive two parameters on the command line. It is required that negative numbers cannot be entered and the two numbers are divided.
         Inconsistent data type (NumberFormatException), missing command line parameter (ArrayIndexOutOfBoundsException
         Exception handling is performed except for 0(ArithmeticException) and negative numbers (EcDef custom exceptions). 
 Tips:
(1)Define an exception method (ecm) in the main class (EcmDef) to divide two numbers. 
(2)Use exception handling statements in the main() method for exception handling. 
(3)In the program, customize the exception class (EcDef) corresponding to the input negative number. 
(4)The runtime accepts the parameter java EcmDef 20 10 //args[0] = "20" args[1] = "10" 
(5)Interger The static method parseInt(String s) of class converts s to the corresponding int value. 
      For example: int a=Interger.parseInt("314"); / / a=314;
 */
public class EcmDef {
	public static void main(String[] args) {
		try {
			int i = Integer.parseInt(args[0]);
			int j = Integer.parseInt(args[1]);
			int result = ecm(i,j);
			System.out.println(result);
		} catch (NumberFormatException e) {
			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)
		{
			System.out.println(e.getMessage());
		}
		
	}

	public static int ecm(int i,int j) throws EcDef
  {
		if(i < 0||j <0)
  {
	throw new EcDef("The numerator or denominator is negative");	
  }
		return i/j;
		
  }
}

16. Summary of exception handling section

  •   throw is a case where an exception object is generated
  • throws is the exception handling performed

  •   Interview question: what is the difference between the three?
  • Similar: throw and throws   collection and collections string buffer StringBuilder
  •         ArrayList and LinkedList   HashMap and LinkedHashMap
  • The difference between overriding and overloading
  • Structure dissimilarity: abstract class interface = = equals() sleep() wait()
  • Compare the two processing methods: try catch finally: the exception is really handled. The throws method only throws the exception to the caller of the method, but does not really handle the exception
  • throw represents the object that throws an exception class and the process of generating an exception object, which is declared in the method body
  • throws is a way of exception handling, which is declared at the declaration of the method

Tags: Java Back-end

Posted on Tue, 26 Oct 2021 03:03:10 -0400 by erikwebb