[JAVA exception handling | try catch, throw, throws]

abnormal

General exception code:

public class Exception01 {
    public static void main(String[] args) {
        int n1 = 10;
        int n2 = 0;
        // n1 / n2 => 10 / 0
        int res = n1/n2;
        System.out.println("The program continues to run");
    }
}

Exception capture (try catch) is set:

public class Exception01 {
    public static void main(String[] args) {
        try{
            int n1 = 10;
            int n2 = 0;
            // n1 / n2 => 10 / 0
            int res = n1/n2;
        } catch (Exception e){
            // TODO:handle exception
            //e.printStackTrace();// Print the exception stack, that is, the code and information output of the exception error
            System.out.println("Abnormal information=" + e.getMessage());
        }
        System.out.println("The program continues to run");
    }
}

Exception introduction

Basic concepts

In the Java language, abnormal conditions occurring in program execution are called "exceptions". (Syntax in development)
Errors and logical errors (not exceptions)

Abnormal events can be divided into two categories (Error,Exception)

  1. Error: a serious problem that the Java virtual machine cannot solve. Such as: JVM system internal error, resource exhaustion and other serious situations. For example: stack overflow error] and oom (out of)
    memory),Error is a serious error, and the program will crash.
  2. Exception: other general problems caused by programming errors or accidental external factors can be handled with targeted code. For example, empty finger access, trying to read a non-existent file, in a network connection
    Break and so on. Exception s are divided into two categories: runtime exceptions [exceptions that occur when the program is running] and compile time exceptions [exceptions checked by the compiler at compile time].

Class diagram:

Common runtime exceptions

  1. Null pointerexception null pointer exception

    String name = null;
    System.out.println(name.length());
    
  2. ArithmeticException mathematical operation exception

    int n1 = 10;
    int n2 = 0;
    int res = n1/n2;
    
  3. ArrayIndexOutOfBoundsException array index out of bounds exception

    int[] arr = {1, 2, 4};
    for (int i = 0; i <= arr.length; i++) {
        System.out.println(arr[i]);
    }
    
  4. ClassCastException type conversion exception

    public class ClassCastException_ {
        public static void main(String[] args) {
            A b = new B();//Upward transformation
            B b2 = (B)b;//Downward transformation, OK
            C c2 = (C)b;//ClassCastException type conversion exception will be thrown here
        }
    }
    
    class A {}
    class B extends A {}
    class C extends B {}
    
  5. NumberFormatException number format is incorrect exception

    String name = "Jack";
    //Parse String to int
    int num = Integer.parseInt(name);
    

Common compile time exceptions

  1. SQLException
  2. IOException
  3. FileNotFoundException
  4. ClassNotFoundException
  5. EOFException
  6. IlldgalArgumentException

exception handling

Basic introduction

Exception handling is the way to handle exceptions when they occur.

Exception handling method

  1. try-catch-finally
    The programmer catches the exception in the code and handles it by himself
  2. throws
    Throw the exception and leave it to the caller. The top handler is the JVM

try-catch-finally

try{
    //Code / possible exception
} catch (Exception e) {
    //Catch exception
    //1. When an exception occurs
    //2. The system encapsulates the Exception into an Exception object e and passes it to catch
    //3. After getting the exception object, the programmer handles it by himself
} finally {
    //You can pass without finally syntax
    //Whether there are exceptions or not, finally, it must be executed
}

throws

Exceptions use throws by default.

try-finally

Using try finally to cooperate directly is equivalent to not catching exceptions, so the program will crash directly. The application scenario is to execute a piece of code. No matter whether an exception occurs or not, a certain business logic must be executed.

try{
    //code......
} finally {
    //Always execute code
}

Try mechanism

TryCatchDetail01.java

Use ctrl + alt + t shortcut to set try catch

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-7aibvacn-164418312071) (. \ image \ image-20211007084308512. PNG)]

public class TryCatch01 {
    public static void main(String[] args) {

        try {
            String str = "Jack";
            int a = Integer.parseInt(str);
            System.out.println("Number:" + a);
        } catch (NumberFormatException e) {
            System.out.println("Abnormal information = " + e.getMessage());
        }

        System.out.println("Program continue......");
    }
}

If you want to execute a piece of code no matter what happens, use finally.

Multiple catch statements can be used to catch different exceptions for different business processing). It is required that the parent Exception is in the rear and the child Exception is in the front. For example (Exception is in the rear and NullPointerException is in the front). If an Exception occurs, only one catch will be matched.

TryCatchDetail02.java

public class TryCatchDetail02 {
    public static void main(String[] args) {
        try {
            Person person = new Person();
            person = null;
            System.out.println(person.getName());//NullPointerException
            int n1 = 10;
            int n2 = 0;
            int res = n1 / n2;//ArithmeticException
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
        }
    }
}

class Person{
    private String name;

    public String getName() {
        return name;
    }
}

Improved multi exception handling:

Subclass exception must be put in front!!!

public class TryCatchDetail02 {
    public static void main(String[] args) {
        try {
            Person person = new Person();
            person = null;
            System.out.println(person.getName());//NullPointerException
            int n1 = 10;
            int n2 = 0;
            int res = n1 / n2;//ArithmeticException
        } catch (NullPointerException e) {
            System.out.println("Null pointer exception: " + e.getMessage());
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic anomaly: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("General anomaly: " + e.getMessage());
        } finally {
        }
    }
}

class Person{
    private String name;

    public String getName() {
        return name;
    }
}

TryCatchDetail03.java

public class TryCatchDetail03 {
    public static void main(String[] args) {
        try{
            int n1 = 10;
            int n2 = 0;
            System.out.println(n1 / n2);
        } finally {
            System.out.println("Yes finally...");
        }

        //It will not continue to run. The program crashes directly after finally running
        System.out.println("The program continues to run...");
    }
}

TryCatchExercise01.java

public class TryCatchExercise01 {
    public static int method(){
        try{
            String[] names = new String[3];
            if(names[1].equals("tom")){//NullPointerException
                System.out.println(names[1]);
            } else{
                names[3] = "hspedu";
            }
            return 1;
            }
        catch (ArrayIndexOutOfBoundsException e){
            return 2;
        }
        catch (NullPointerException e){
            return 3;
        }
        //Since finally must be executed, 4 must be returned
        finally{
            return 4;
        }
    }

    public static void main(String[] args) {
        System.out.println(method());
    }
}

TryCatchExercise02.java

public class TryCatchExercise02 {
    public static int method(){
        int i = 1;
        try{
            i++;//2
            String[] names = new String[3];
            if(names[1].equals("tom")){//NullPointerException
                System.out.println(names[1]);
            } else{
                names[3] = "hspedu";
            }
            return 1;
        }
        catch (ArrayIndexOutOfBoundsException e){
            return 2;
        }
        catch (NullPointerException e){
            return ++i;//3
        }
        //Since finally must be executed, 4 must be returned
        finally{
            return ++i;//4
        }
    }

    public static void main(String[] args) {
        System.out.println(method());//4
    }
}

TryCatchExercise03.java

public class TryCatchExercise03 {
    public static int method(){
        int i = 1;//1
        try{
            i++;//2
            String[] names = new String[3];
            if(names[1].equals("tom")){//NullPointerException
                System.out.println(names[1]);
            } else{
                names[3] = "hspedu";
            }
            return 1;
        }
        catch (ArrayIndexOutOfBoundsException e){
            return 2;
        }
        catch (NullPointerException e){
            //Return 3
            return ++i;//3
        }
        finally{
            ++i;//4
            System.out.println("i = " + i);//i = 4
        }
    }

    public static void main(String[] args) {
        System.out.println(method());//3
    }
}

TryCatchExercise04 – get input with exception capture

public class TryCatchExercise04 {
    /* 1.Create Scanner
     * 2.Use an infinite loop to accept an input
     * 3.Then convert the input value to int
     * 4.If an exception is thrown during conversion, the input cannot be converted to int
     * 5.If not thrown, break the loop*/
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int num = 0;
        while (true) {
            System.out.println("Please enter an integer:\n");
            try {
                num = Integer.parseInt(scanner.next());
                break;
            } catch (NumberFormatException e) {
                System.out.println("Error in input, please re-enter!\n");
            }
        }
        System.out.printf("Your input is: " + num);
    }
}

Throws mechanism

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 the exception.

Use the throws statement in the method 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.

Throws01.java

public class Throws01 {
    public static void main(String[] args) {

    }

    //public void f1() throws Exception can also be used
    public void f1() throws FileNotFoundException, NullPointerException {
        //Created a file stream object
        //The exception here is a FileNotFoundException
        //You can use try catch
        //You can also use throws to throw an exception and let the caller () calling the fi method handle it
        //The throws keyword can also be followed by a list
        FileInputStream fis = new FileInputStream("dd.txt");
    }
}

ThrowsDetail.java

  1. For compilation exceptions, they must be handled in the program, such as try catch or throws

  2. For runtime exceptions, if they are not handled in the program, they are handled by the throws method by default

  3. When the subclass overrides the method of the parent class, the provisions on throwing exceptions: the exception type thrown by the method overridden by the subclass is either the same as that thrown by the parent class, or the subtype of the exception type thrown for the parent class.

    class Father {
        public void method() throws RuntimeException{
        }
    }
    
    class Son extends Father {
        //When the subclass overrides the method of the parent class, the rules for throwing exceptions are as follows:
        // The exception type thrown by the method overridden by the subclass is either the same as that thrown by the parent class,
        // Or throw a subtype of the exception type for the parent class.
        @Override
        public void method() throws NullPointerException {
    
        }
    }
    

Handling of compilation exceptions

Solution 1: use try catch processing

Solution 2: throws

Handling of running exceptions

Custom exception

When there are some "errors" in the program, but the error is not described in the Throwable subclass, you can design your own exception class to describe the error information.

Custom exception steps

  1. Definition class: custom exception class name, inheriting expectation or rnntimeexpectation
  2. If you inherit expectation, it is a compilation exception
  3. If you inherit runtimeexpectation, it is a running exception (generally inherit runtimeexpectation)

CustomException.java

public class CustomExpection {
    public static void main(String[] args) {
        int age = 800;
        //The age is required to be between 18-120 1, otherwise an exception is thrown
        if (!(age >= 18 && age <= 120))
        {
            throw new AgeException("Need at age 18~120 between!");
        }
        System.out.println("Your age range is correct!");
    }
}

//Custom exception
//1. Generally, custom exceptions inherit RuntimeException, that is, runtime exception
//2. The advantage is that we can use the default processing mechanism
class AgeException extends RuntimeException {
    //constructor 
    public AgeException(String message) {
        super(message);
    }
}

The difference between throw and throws

significancepositionWhat follows
throwsA way of exception handlingMethod declaration OfficeException type
throwsKeywords for manually generating exception objectsMethod bodyException object

Keywords: Java Back-end

Added by Spaceman-Spiff on Sun, 06 Feb 2022 08:27:21 +0200