Material transcoding log [5] – exception handling

Foreword (2023.4.21)

Understand exception concepts, classification, and exception capture and handling. It is mainly for exception capture for errors that occur during runtime.

Exception handling

Throwable (class)

Subclass:

  1. error
  2. Exception

The concept of exception

Exception: Refers to abnormal events that occur when the program is running. The exception can be handled by the program to ensure that the program continues to run;
Error: The error program cannot be processed. After an error occurs, the general virtual machine chooses to terminate the program, and the programmer needs to modify the relevant code to solve the relevant error.

Exception classification

It is generally divided into Checked (checking) exceptions and Runtime exceptions. All instances of the RuntimeException class and its subclasses are called Runtime exceptions, and exceptions that do not belong to this category are called CheckedExceptions.

CheckedException:

java.lang.ClassNotFoundException
java.lang.NoSuchMethodException
java.io.IOException

runtimeException:

java.lang.ArithmeticException
Java.lang.ArrayStoreExcetpion
java.lang.ClassCastException
java.lang.IndexOutOfBoundsException
java.lang.NullPointerException

package com.zxy.April21;

public class TestException {<!-- -->
    static String str;//Default value is null
    static int[] array1 = {<!-- -->1,3,5};
    static int i = 2, j = 0;
    static Pig pig = new Pig();

    public static void main(String[] args) {<!-- -->
        //1. A null pointer exception occurs here
        System.out.println(str.length());

        //2. Array subscript out of bounds exception
        array1[3] = 1;
        
        //3. Arithmetic exception (including divisor cannot be 0 exception)
        System.out.println(i / j);

        //4. Class conversion exception
        Object object = pig;
        TestZoo zoo = (TestZoo) object;

        //It will not be executed here
        System.out.println("Here is the normal execution code");
    }
}

Exception capture and handling

Method 1: try-catch-finally

  • try-catch-finally
 try{<!-- -->
// monitoring function
\t
}catch (exception){<!-- -->
// catch and process
\t
}finally{<!-- -->
// Regardless of whether an exception occurs, the statements in the finally statement block are always guaranteed to be executed
//finally statement block is mainly used to solve the problem of resource leakage
}
  • try-catch
static String str;//Default value is null
public static void main(String[] args) {<!-- -->
        try{<!-- -->
            //try stores the code that may cause an exception
            //1. A null pointer exception occurs here
            System.out.println(str.length());
        }catch (NullPointerException e){<!-- -->//catch is to catch the exception, and the parentheses are the exception type reference name
            //There are many exception handling methods, just choose one of the three
            System.out.println("null pointer exception");
            e.printStackTrace();//print stack trace
            System.out.println(e.getMessage());//abnormal error message, return is a string
        }
        System.out.println("Here is the normal execution code");

After processing, the program can continue to run normally

  • try-catch-catch…
 static String str;//Default value is null
    static int[] array1 = {<!-- -->1,3,5};
    static int i = 2, j = 0;
    static Pig pig = new Pig();

    public static void main(String[] args) {<!-- -->
        try{<!-- -->
            //try stores the code that may cause an exception
            //1. A null pointer exception occurs here
            System.out.println(str.length());//Output a null pointer exception, after the catch is caught, the code behind the try will not be executed

            //2. Array subscript out of bounds exception
            array1[3] = 1;

            //3. Arithmetic exception (including divisor cannot be 0 exception)
            System.out.println(i / j);

            //4. Class conversion exception
            Object object = pig;
            TestZoo zoo = (TestZoo) object;
        }catch (NullPointerException e){<!-- -->//catch is to catch the exception, and the parentheses are the exception type reference name
            //There are many exception handling methods, just choose one of the three
            //System.out.println("null pointer exception");
            e.printStackTrace();//print stack trace
            //System.out.println(e.getMessage());//The abnormal error message returns a string
        }catch (ArrayIndexOutOfBoundsException e){<!-- -->
            System.out.println("Array out of bounds exception");
        }catch (Exception e){<!-- -->//It can only be placed at the end, and its direct subclass or indirect subclass should be placed in front, and the small ones should be placed before the big ones
            System.out.println("Arithmetic exception");
        }

        System.out.println("Here is the normal execution code");
    }
}

You can put a lot of code that may cause exceptions in try, but only one can be caught at a time for processing
less subdivided
There is another kind: Note: There can be multiple catches behind the try, but pay attention to the hierarchical relationship: the higher the level, the lower the level.

  • try…finally
  • finally-> always execute
import java.util.Scanner;

public class TestFinally {<!-- -->
    public static void main(String[] args) {<!-- -->
        Scanner scanner = new Scanner(System.in);
        try{<!-- -->
            //There is an exception here
        }finally {<!-- -->
            //No matter what, it will be executed
            //Database access, release of resources, release of IO resources, etc.
            if (scanner != null){<!-- -->
                scanner. close();
            }
        }
        
        try{<!-- -->
            
        }catch (Exception e){<!-- -->
            //An exception occurs and is caught before execution
        }finally {<!-- -->
            //No matter what, it will be executed
        }
    }
}

Notes:

1. There is a return statement before the finally block, and finally is still executed;
2. If there is a System.exit(0) statement before the finally block, finally will not be executed;

 try{<!-- -->
            System.out.println(1/0);
        }catch (Exception e){<!-- -->
            System.out.println("An exception occurred, the divisor cannot be 0");
            return;//end method
        }finally {<!-- -->
            System.out.println("finally code block");
        }
        System.out.println("The main method is finished");
    }
 try{<!-- -->
            System.out.println(1/0);
        }catch (Exception e){<!-- -->
            System.out.println("An exception occurred, the divisor cannot be 0");
            //return;//end method
            System.exit(0);//end jvm running
        }finally {<!-- -->
            System.out.println("finally code block");
        }
        System.out.println("The main method is finished");
    }

Two classic questions

1. If there is no exception, test the execution order of the return statement in try and finally. First execute the return in try, then execute the return in finally, and finally the return in finally shall prevail.
2. There is return in try, but there is no return in finally, then the result is subject to try

Method 2: throws (throws an exception)

The exception has been thrown upwards, and the culmination is that the JVM can be said to have declared an exception. It can be understood as throwing an exception, which is thrown to the caller, and whoever calls him will throw it to whom;
throws is used at the method declaration to declare the exception types that may occur in the method; multiple types can be declared after throws, separated by commas

public class TestThrows {<!-- -->
    static String str;//Default value is null
    /*public static int method1(){
        int i = 1;
        try {
            i + + ;
            return i;
        }catch (Exception e){

        } finally {
            return 0;
        }
}*/
    public static void main(String[] args) {<!-- -->
        try{<!-- -->
            method1();
        }catch(NullPointerException e){<!-- -->
            //e.printStackTrace();
        }
        System.out.println("Here is the normal execution code");
    }

    public static void method1() throws NullPointerException{<!-- -->
        System.out.println(str.length());
    }
}

Method 3: throw: Manually throw an exception (understand)

Manually raise an exception, which occurs in a method (I think that an exception occurs when a certain condition is met)
? Throwing an exception is actually creating an exception object, and then using the throw keyword to hand it over to the exception handling mechanism for processing;
? The throw keyword is used in the method body, as follows:

 public static void main(String[] args) {<!-- -->
        try{<!-- -->
            method1();
        }catch(Exception e){<!-- -->
            //e.printStackTrace();
        }
        System.out.println("Here is the normal execution code");
    }
    public static void method1() throws Exception{<!-- -->
        int i=1,j=0;
        if(j == 0){<!-- -->
            //The condition is met, it will be executed here, as long as the code here is executed, it proves that an exception will definitely occur
            //What should I do if an exception occurs? It must be handled, and the exception handling can use try or throws
            throw new Exception("Here is the exception I threw manually");
        }
        System.out.println("" + i / j);
    }

Method 4: Custom exception (understanding)

Create a custom exception class:
① Inherit Exception (or its subclasses)
② Add a parameterized structure
③Rewrite getMessage()-writable or not

/**
 * Customize an age exception class
 * @author ZhangXy
 */

class ageException extends RuntimeException {<!-- -->

    public ageException(){<!-- -->
        }
    // Construct with parameters
    public ageException(String message){<!-- -->
        //His parent class is RuntimeException, pass this information in
        //When you have a new class with parameters, do you first call the parent class with parameters?
        //Then pass in the defined information and you can print it
        super(message);
        }
}
class students{<!-- -->
    private String stuName;
    private int age;

    public String getStuName() {<!-- -->
        return stuName;
    }

    public void setStuName(String stuName) {<!-- -->
        this.stuName = stuName;
    }

    public int getAge() {<!-- -->
        return age;
    }

    public void setAge(int age) {<!-- -->
       if (age <= 0){<!-- -->
           // Manually raise an exception
           throw new ageException("The age is invalid, at least greater than 0");
       }
        this. age = age;
    }

    public students() {<!-- -->
    }

    public students(String stuName, int age) {<!-- -->
        this.stuName = stuName;
        this. age = age;
    }

    @Override
    public String toString() {<!-- -->
        return "students{" +
                "Student Name='" + stuName + ''' +
                ", student age=" + age +
                '}';
    }


}
public class TestThrow{<!-- -->
    public static void main(String[] args) {<!-- -->
        students stu = new students();
        stu.setAge(0);
    }

}

Exception summary

Exceptions are some errors in a program, but not all errors are exceptions, and errors are sometimes avoidable. ?
Checked exceptions: The most representative checked exceptions are exceptions caused by user errors or problems, which cannot be foreseen by the programmer. For example, an exception occurs when trying to open a file that does not exist, and these exceptions cannot be simply ignored at compile time.

1. Classification: compile-time exception, runtime exception
2.Exception: Generally, it is an error in logic or data content
Error: various exceptions at the bottom of jvm: memory overflow, stack overflow.
3. All programming languages need exception handling, which is aimed at “runtime”.
4. Handling of abnormal effects: Prepare in advance to avoid program “termination” due to exceptions.
5. Java.lang.Exception of the parent class of all exception classes
6. Four direct subclasses of Exception

  • SQLException – database exception
  • ClassNotFountdException – class not found
  • IOException – stream exception
  • RuntimeException – runtime exception

7.RuntimeException-Common subclasses of runtime exceptions
ArithmeticException Arithmetic exception, such as: division by 0 IllegalArgumentException
The method received an illegal parameter ArrayIndexOutOfBoundsException Array subscript out of bounds NullPointerException
Accessing a null reference ClassNotFoundException Unable to load required class NumberFormatException
String conversion to number failed

8. Exception handling
Method 1:

 try{<!-- -->
> //Monitoring function, monitor possible exceptions
> }catch(){<!-- -->
> // capture function to do processing
> }finally{<!-- -->
> // No matter what happens in try, finally will be executed, unless there are special circumstances
> }

Note: There can be multiple catches behind the try, but pay attention to the hierarchical relationship: the lower the class level, the higher the level, and the higher the level, the lower the level.
finally is not always executed. Some special cases: exception in finally statement, exit program…
Method 2: The throws statement is used to throw an exception: the exception is not handled in the method, and it is thrown upwards.
Method 3: The throw statement is used to manually throw exceptions, which is rarely used
Way 4: Custom exception, customize an exception class

Common interview questions

①What is the difference between Exception and error?

Both inherit from Throwable.
Exception: It can be checked, it is an abnormal event during the running process, it can be handled by the exception mechanism, and the program can continue to run;
Error: various problems at the bottom of jvm: memory overflow, stack overflow. Errors cannot be handled. After an error occurs, the program terminates, and the programmer needs to modify the source code to solve the error;

② What is the role of the try catch finlly keyword?

try: monitoring role
catch: catch exception, handle exception
finally: Regardless of whether an exception occurs, the code block in finally will be executed. The finally block is optional, and it can be decided whether to add it according to the specific situation;
The finally block must be used together with the try block and cannot exist alone.
Note: There is a return statement before the finally block, and finally is still executed;
There is a System.exit(0) statement before the finally block, and finally is not executed;

③ In the case of no exception, test the execution order of the return statement in try and finally?

Execute the return in try first, then execute the return in finally, and finally the return in finally shall prevail.
There is return in try, but there is no return in finally, then the result is subject to try

④ What is the difference between throws and throw in exception handling?

The role is different: throw is used for programmers to generate and throw exceptions themselves; throws is used to declare that exceptions are thrown in this method
The location of use is different: throw is located inside the method body and can be used as a separate statement; throws must follow the method parameter list and cannot be used alone.
The content is different: throw throws an exception object, and there can only be one; throws is followed by the exception class, and there can be multiple.