Advanced Java exception

Keywords: Java Exception

preface

Complete the introduction to Java exceptions first , and then complete Java advanced.

1, Automatically close resources

The JVM does not recycle hardware resources (such as I/O resources). That is what the OS does. The JVM will recycle the resources occupied by objects in heap memory.
When IOException occurs in the I/O flow, the following code will be stopped, resulting in that the I/O flow cannot be closed. So use Finally to recycle.

public void testCheckedException() {
        FileReader reader = null;
        try {
            reader = new FileReader("d:\\a.txt");
            char ch = (char) reader.read();
        } catch (FileNotFoundException e) {
            //Print stack track
            e.printStackTrace();
            //Print information in stack
            StackTraceElement[] els = e.getStackTrace();
            for(StackTraceElement el : els){
                System.out.println("Class where exception occurs:"+ el.getClassName());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

After JDK1.7, try appears_ with_ Resources mechanism:
Any class that inherits the autoclosable class can automatically call the close method to close the resource flow when the try statement block exits.

public void testCheckedException2() {
        try(FileReader reader = new FileReader("d:\\a.txt"); FileOutputStream fos = new FileOutputStream("d:\\a.txt")) {
            char ch = (char) reader.read();
        } catch (FileNotFoundException e) {
            //Print stack track
            e.printStackTrace();
            //Print information in stack
            StackTraceElement[] els = e.getStackTrace();
            for(StackTraceElement el : els){
                System.out.println("Class where exception occurs:"+ el.getClassName());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

2, Multi exception capture

When multiple exceptions occur in the try statement,
1) It can be separated by |.
2) If a catch statement block handles more than one exception type (two types of exceptions have no inheritance relationship), the catch parameter variable is implicitly changed to final variable, and it can no longer be assigned in the catch statement block, that is, the current object reference can not point to other objects.

public void testCheckedException2() {
        try(FileReader reader = new FileReader("d:\\a.txt"); FileOutputStream fos = new FileOutputStream("d:\\a.txt")) {
            char ch = (char) reader.read();
            int num = 2 / 0;
        } catch (IOException | ArithmeticException e) {
            //Print stack track
            e.printStackTrace();
            //Print information in stack
            StackTraceElement[] els = e.getStackTrace();
            for(StackTraceElement el : els){
                System.out.println("Class where exception occurs:"+ el.getClassName());
            }
        }
    }

3, Exception handling nesting

Can you use multiple catch statements instead of exception handling nesting?

public void embedException() {
        try {
            //Procedure A
            try {
                //Procedure B
            } catch (RuntimeException e) {
                //Procedure C
            } finally {
                //Procedure D
            }
            //Procedure E
        } catch (Exception e) {
            //Procedure F
        } finally {
            //Procedure G
        }
    }
public void embedException2() {
        try {
            //Procedure A
            //Procedure B
        } catch (RuntimeException e) {
            //Procedure C
        } catch (Exception e) {
            //Procedure F
        } finally {
            //Program D, previous finally statement.
            //Procedure E
            //Procedure G
        }
    }

1) No exception: ABDEG
2) A abnormal: AFG
Note: if A is abnormal, the following BDE will not be executed
3) B exception: ABCDEG, when no catch is caught in the inner layer, the outer catch is executed, which is another execution path.
4) Summary: when an exception occurs, the following executed statements will be stopped. After processing, the processed statements can be executed. Finally statement must be executed.

4, catch + throws to wrap exceptions

public void packException() throws Exception {
        try {
            int n = 2 / 0;
        } catch (ArithmeticException e) {
            throw new Exception("Divisor cannot be 0");
        }
    }

5, Exception chain tracking information

An exception is thrown after an exception is caught, and the original exception information that causes the exception is saved and passed on, which is called an exception chain.

public void packException2() throws Exception {
        try {
            int n = 2 / 0;
        } catch (ArithmeticException e) {
            throw new Exception("Divisor cannot be 0",e);
        }
    }
/**
     * Constructs a new exception with the specified detail message and
     * cause.  <p>Note that the detail message associated with
     * {@code cause} is <i>not</i> automatically incorporated in
     * this exception's detail message.
     *
     * @param  message the detail message (which is saved for later retrieval
     *         by the {@link #getMessage()} method).
     * @param  cause the cause (which is saved for later retrieval by the
     *         {@link #getCause()} method).  (A {@code null} value is
     *         permitted, and indicates that the cause is nonexistent or
     *         unknown.)
     * @since  1.4
     */
    public Exception(String message, Throwable cause) {
        super(message, cause);
    }

6, Friendly throws statement

public void friendlyThrows() throws IOException {
        try (FileReader reader = new FileReader("d:\\a.txt")){
            //Operation file
        }catch (Exception e){
            //Abnormal operation
            throw e;
        }
    }

When we catch the Exception and throw it out, the Java compiler will carefully check the actual Exception, and then throw the real Exception IOException

summary

1) Automatically close resources
2) Multi exception capture
3) Exception handling nesting
4) catch + throws to wrap exceptions
5) Exception chain tracking information
6) Friendly throws statement

Posted by bradsteele on Wed, 03 Nov 2021 22:24:41 -0700