exception catch example

package Test;
public class Test {
    private static void test(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            try {
                if (arr[i] % 2 == 0) {
                    throw new NullPointerException();
                } else {
                    System.out.print(i);
                }
            } finally {
                System.out.print("e");
            }
        }
    }
 
    public static void main(String[]args) {
        try {
            test(new int[] {0, 1, 2, 3, 4, 5});
        } catch (Exception e) {
            System.out.print("E");
        }
    }
 
}

 Since arr[0] = 0, a NullPointerException will be thrown on the first if when entering the test() method, and then the finally statement will be executed,

(The finally statement is executed before the return and throw statements), output an 'e, and then return to the main method. Since the exception is caught, it enters the catch statement, and then prints an 'E', so the final result is "eE"

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324838613&siteId=291194637