[Java basics] detailed explanation of exception technology in Java

What is an exception

An error that can be handled by a java class is called an exception

A set of mechanisms used in Java to find problems, feed back problems and solve problems

Exception direct subclass

  • Throwable: the top-level parent of the exception

Exception: exception

It is a reasonable application, which can be processed or not

  1. The runtime exception can be ignored
    • ArithmeticException: arithmetic exception
    • ArrayIndexOutOfBoundsException: array subscript out of bounds exception
    • ClassCastException: type conversion exception
    • NullPointerException: null pointer exception
    • NumberFomatException: number format exception
  2. Compile time exception, must be handled
    • IOException: IO exception
    • FileNotFoundException: exception not found in file
    • CloneNotSupportException: cloning does not support exceptions
    • ParseException: parse exception

Error: an error that cannot be handled by code

Reasonable applications are generally caused by the external environment or requirements

Handling exceptions

Method rewriting

Number and level of subclass exceptions < = parent exception

Method throws as many compile time exceptions as it catches

try-catch

Throw multiple exceptions for unified processing. Find the unified parent class of multiple exception classes for unified capture

  1. try: put the code that generates the exception

  2. Catch: catch exception

    • There are several ways to deal with it

      codeUse
      System.out.println("file does not exist");//1. Show it to the customer
      System.out.println(e.getMessage());//2. For programmers
      e.printStackTrace();//3. Print stack information for programmers
      (print exception stack track)
    • (): used to match the type of exception in the try block

    • Packet capture:

      Catch multiple exceptions thrown, and use | to divide a group of exception classes (JDK1.7)

      try{
          
      }catch (NullPointerException | ArrayIndexOutOfBoundsException e){
      
      }
      

throws

Declare exception

Throw an exception when a method is declared

Who handles exceptions with who

🥇 If the main method throws an exception, the exception handling is handed over to the jvm

package demoException;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
 
public class DemoException {

	/**
	 * No error at compile time, runtime error ------ runtime exception RuntimeException
	 * 
	 * Run time exceptions can not be handled. If the code is written carefully, there will be no exceptions
	 */
	public static void test1() {
		int x = 1/0;//Exception except 0
		System.out.println(x);
		
		int[] a = new int[3];
		System.out.println(a[3]);//The following table of the array is out of bounds
	}
	
	/**
	 * Exception generated during compilation CheckException ----- exception must be handled during compilation
	 * @param args
	 */
	public static void test2() {
		//try puts the code that generates the exception
		try {
			FileInputStream input = new FileInputStream("a.txt");
		} catch (FileNotFoundException e) {
			//Catch catch exception
			//There are several ways to deal with it
			System.out.println("file does not exist");//1. For customers
			System.out.println(e.getMessage());//2. For programmers
			e.printStackTrace();//3. Print stack information for programmers
		}
	}
	//throws declaration exception
	public static void test3() throws FileNotFoundException {
		FileInputStream input = new FileInputStream("a.txt");
	}
 
	//If the main method throws an exception, the exception handling is handed over to the jvm
	public static void main(String[] args) throws FileNotFoundException {
		test3();
	}
 
}
 

finally

No matter whether the try block or catch block is executed or not, the contents in the finally block will be executed

Common code formats for exceptions

//Common code format of exception: try can follow multiple catch es
		
//When there are multiple catch blocks, the order of capture -- > from small to large
public static void test4() {
    try {
        FileInputStream input = new FileInputStream("a.txt");
        input.read();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }
}

public static void test5() {
    try {
        FileInputStream input = new FileInputStream("a.txt");
        input.read();
    } catch (Exception e) {//The Exception is the largest. I don't know who is big. Write the Exception directly and catch all exceptions
        e.printStackTrace();
    }
}


//Throw an exception. Multiple exceptions are separated by "," and there is no sequence of exceptions,
public static void test6() throws FileNotFoundException,IOException{
    FileInputStream input = new FileInputStream("a.txt");
    input.read();
}


//Write Exception directly and catch all exceptions
public static void test7() throws Exception {
    FileInputStream input = new FileInputStream("a.txt");
    input.read();
}


//finally
public static void test8() {
    FileInputStream input = null;
    try {
        input = new FileInputStream("a.txt");
        input.read();
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        //Whether there are exceptions or not, the last piece of code to be executed
        if(input!=null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

//You can't have more than one try and one catch

//Try finally is syntactically correct, but this exception cannot be handled
public static void test10() throws FileNotFoundException {
    FileInputStream input = null;
    try {
        input = new FileInputStream("a.txt");
    }finally {

    }
}

Exception of inheritance relationship

Inheritance diagram

[the transfer of external chain pictures fails. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (IMG mayagqum-1614316595289) (E: \ Java notes \ API learning notes \ 1.png)]

Exception limitation during java method rewriting (compile time exception)

  1. When a subclass overrides a method whose parent class has an exception declaration, the subclass:
    • Do not throw exceptions
    • Throw the same exception as the parent method or the subclass of the exception
  2. When the subclass overrides the method with exception declaration of the parent class, and also implements the interface with the same method name, and the method in the interface also has exception declaration, the subclass:
    • Do not throw exceptions
    • The intersection of throwing a parent method declaration exception and an interface method declaration exception
package demoException;
 
import java.io.IOException;
 
class A{
	public void f() throws IOException{
	}
}
 
//Exception refers specifically to the exception generated during compilation
public class DemoException2 extends A{
	public void f() throws IOException,RuntimeException{
		//You can declare more than one, but it must be smaller than the parent exception
		//RuntimeException: run is an exception, which specifically refers to compile time exception. Throwing a run-time exception has no effect
	}
 
}
 

Custom exceptions and usage

Custom exception class

  • If the custom exception class inherits other classes except RunTimeException and subclasses, it is a compile time exception by default
package demoException;
 
//The custom Exception class must inherit the Exception class (Exception, or any Exception)
public class AgeIllException extends Exception{
	public AgeIllException() {
		//Call the constructor with parameters of the parent class to pass exception information
		super("Please enter the correct age (1)-130)");
	}
 
}

Student implementation class

There can only be one exception object after how

You can declare multiple exceptions after thows

package demoException;
 
public class Student {
	private int age;
 
	public int getAge() {
		return age;
	}
 
	public void setAge(int age) throws AgeIllException {
		if(age<=0||age>130) {
			throw new AgeIllException();//Throwing anomaly
		}
		this.age = age;
	}
 
	public static void main(String[] args) {
		Student stu = new Student();
		try {
			stu.setAge(230);
			System.out.println(stu.getAge());
		} catch (AgeIllException e) {
			System.out.println(e.getMessage());
		}
	}
}

Try finally question

numerical value

Return 1

public static int m1(){
    int i = 1;
    try {
        /*
            Execute to try block content, return i + +--- return 1ï¼›
            When the program is finally executed, be sure to return the content in the following execution block
            Java return 1; The function, status and return value of this code will be suspended
            After hanging, execute the contents in the finally block, I + + -- 3; completion of enforcement
            When the finally block is executed, Java will go back and execute the suspended content return 1;
             */
        return i++;
    }finally {
        i++;//3
    }
}

Return: 2

public static int test2(){
    int i = 1;
    try {
        return i++;//This return is suspended
    } finally {
        return i++;
        //This return must run to, but it is a return statement, which will directly return the i here++
    }
}

object

Return Person{name='jack', gender = male, age=17}

In try, return suspends the address value of p

public static Person m2(){
    Person p = new Person();
    p.name = "lili";
    p.age = 10;
    p.gender = 'female';
    try {
        p.name = "tom";
        p.age = 11;
        p.gender = 'male';
        return p;
    } finally {
        p.name = "jack";
        p.age = 17;
        p.gender = 'male';
    }

}

String

Hello is returned

return in try is the address value that str points to Hello

public static String test1(){
        String str = "Hello";
        try {
            return str;
        } finally {
            str = "Hello World";
        }
    }

Tags: Java Programming jvm Android Exception

Posted by Zephyris on Fri, 15 Apr 2022 08:36:50 +0930