2022/07/29 jisoft Java Foundation (14) exception handling

1, What is exception handling
Exception handling is also called exception handling. There are two purposes to deal with exceptions in the program, one is to find the exceptions in the program, and the other is to operate the exceptions relatively or notify the programmer to modify them. Using the try catch statement can accomplish these two purposes well. Like other control statements, the try catch statement also has a basic syntax format. Its basic syntax format is:

try{
Codes with possible exceptions
}Catch (exception type 1 reference){
/ / processing code of exception type 1
}

1.1. Examples:

public class Test2{
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        try {
            System.out.println(a/b);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

1.2. Handle multiple exceptions:
In java, you can also handle multiple exceptions, that is, try multiple catches. It should be noted that when an exception occurs in the code in the try statement block, no matter whether the following code has an exception or not, it will not continue to run, but directly look for the catch statement with the corresponding exception. If there is a corresponding, execute the contents of the catch statement. If there is no corresponding, directly output the exception. For example:

public class Test2 {
 
    public void method() {// Define the called method
        System.out.println("Call a method in a class");
    }
 
    public static void main(String[] args) {
        // TryCatchTest3 tct=null; // Create an empty reference
        Test2 tct = null;
        int[] is = new int[3];
        try {// Include the code that may cause exceptions in this statement
            tct.method(); // Call method with empty reference
            is[3] = 5;
        } catch (NullPointerException e) {// Judge whether the code has null pointer exception
            System.out.println("Null pointer exception occurred");
        } catch (ArrayIndexOutOfBoundsException e) {// Determine whether an array out of bounds exception occurs
            System.out.println("Array out of bounds exception occurred");
        }
    }
 
}

1.3. finally statement:
The use of finally statements is that the contents of finally statements will be executed no matter whether there is an exception in the previous code. There can only be at most one finally statement in an exception handling statement, which can be left blank. Finally statement is very important in actual development. For example, in database operation, it is possible to connect successfully or fail when connecting to the database, but whether it is successful or not, the connection must be closed in the end. The code statement that closes the connection can be placed in the finally statement.

1.4. Precautions for try catch finally statement:
Incomplete forms can also exist in try catch finally statements, such as the form without finally statements seen above. In addition, the catch statement can also be omitted, so that the finally statement follows the try statement. But finally and catch statements cannot be omitted at the same time. If omitted, such Exception handling is meaningless. When there are multiple catch statements in the try catch Exception handling statement, you must put the subclass Exception in front and the parent Exception behind. It can also be said that the exceptions with small scope are put in front and the exceptions with large scope are put behind. For example, Exception is the parent class of all exceptions, while arithmetic exceptions are only handled for specific exceptions, so arithmetic exceptions must be put in front and Exception exceptions in the back.

2, Error:
The Error class is mainly used to represent fatal errors in programs, such as serious errors such as insufficient memory, which are generally related to hardware. There is no need to deal with this Error.

3, throw keyword:
throw of exceptions can be divided into two categories
(1) automatically thrown by the system

(2) throw the exception object display through the throw keyword

To some extent, displaying and throwing exceptions separates the exception handling code from the normal process code, which ensures the relative integrity of the main line of the program and increases the readability and maintainability of the program. The exception is thrown along the call level and handed over to the method that calls it. Syntax of exception thrown:

throw new exception class ();

The exception class must be throwable class and its subclasses

If a method can cause an exception but does not handle it, it must specify this behavior so that the caller of the method can protect themselves from exceptions. To do this, you can include a throws clause in the method declaration. Throws always appears in a method header to indicate various exceptions that may be thrown by the member method.

public class Test2 {
 
    public void method() throws RuntimeException {
        try {
            int[] is = new int[3]; // Define an array with an array length of 3
            is[3] = 5; // Set array elements with index 3
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array out of bounds exception occurred");
            throw e; // Explicit throw caught exception
        }
    }
 
    public static void main(String[] args) {
        Test2 tt = new Test2();
        try {
            tt.method(); // Call method
        } catch (RuntimeException e) {// Handle exceptions thrown in methods
            System.out.println("Reprocess exceptions");
        }
    }

Tags: Java programming language

Posted by bothwell on Sat, 06 Aug 2022 21:26:11 +0300