Finally, catch and return, do you really know how to use it?

1. First briefly introduce the error (Error) and exception (Exception) in Java

In the java.lang package there is a java.lang.Throwable class which is the parent class for all errors and exceptions.

Error:

    Is the parent class of all errors in Java, generally virtual machine-related problems, such as system crashes, virtual machine errors, dynamic link failures, etc. For this kind of task, usually the application cannot handle this kind of error, and it does not need the developer to deal with it, so the application does not need to use cath to capture the Error object, nor does it need to declare the Error error that may occur in the method in the throws clause.

Exception:

        There are two types of exceptions: checkedException and RuntimeException.

        Compilation exceptions: When compiling, you know whether exceptions will occur. If these exceptions are not thrown, the capture will not pass the compilation. For example, when using Java's io to read a file , the file may not exist. ; There are also calling blocking methods (wait, sleep), interrupt blocking will call interrupt externally, then an InterruptedException will be thrown. For these exceptions, the system is prepared for the worst and must be handled (caught or thrown) manually . Otherwise, the compiler cannot pass normally, and this exception requires try-catch.

        Runtime exception: An exception that may occur at runtime, which was not known before. For example, the array index out of bounds (ArrayIndexOutOfBoundsException), the null pointer exception (NullpointerException), the divisor is 0 (ArithmeticException) for these exceptions to be thrown, it is up to the user to decide, because it is not known whether there will be an exception or not, and it is not mandatory to do so. must be dealt with.


exception handling process

  There are two ways: try{ }catch{ }finally{ } and throws

     Put the exception program that will appear in the try block, interrupt the current code to execute the content in catch{ } when an exception occurs, and finally execute finally.    

    The throws keyword is generally used after the method name. Generally, there may be many situations in which the developer is not sure what exception will occur. In this case, add the throws keyword to throw. The developer who calls this method must catch the exception or continue to throw the exception, pass the exception, and hand it over to its father for processing.

    Throw is generally used in methods to throw user-defined exceptions such as throw new MyException ("user-defined exception")

2. finally、return:

    a. Will the code in finally always execute?

Answer: no, ( two cases ) if a method returns before executing the try{} statement , the finally statement will not be executed. Because there is no entry into the try statement at all. If the System.exit(0) ; method is called in a try statement, the current java virtual machine will be exited , and finally there will be no chance to execute. (Of course, there are extremes, that is, when the try is executed, it is suddenly killed and the power is cut off)

    b. Finally execute before return or after return?

 Answer: It is executed in the middle of return


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

    public static int method(){
        int x = 1;
        try {
            return x;
        } catch (Exception e){
            return 0;
        }finally {
            System.out.println("Test");
            ++ x;
        }
    }
}

Result: Output Test first, next line 1

Implementation process:

        First, the return method is executed, and the corresponding value is returned, and the value is stored in the temporary stack. The temporary stack is now 1. But it will not return immediately, but also execute the finally method. After the execution, call return. At this time, it is not a return value, but tells the main program that the execution has been completed, and other methods can be executed. But at this time, the temporary stack still saves the value of 1 in the stack.

  

public class Test {
    public static void main(String[] args) {
        System.out.println(method());
    }
    public static int method(){
        try {
            return 1;
         // System.out.println("Test");
        } catch (Exception e){
            return 0;
        }finally {
            return 2;
        }
     //  System.out.println("Test");
    }
}

Result: 2

Implementation process:

        When return 1 is executed, the temporary stack is 1, and then return 2 in finally is executed, which will overwrite the previous 1, so 2 is returned.

Note: The two output programs above cannot be reached.

Don't understand? Two more:

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

    public static int method(){
        int a = 0;
        try {
            a = 1;
            return a;
        }finally {
            a = 2;
            System.out.println(a);
        }
    }
}

output: 2,1

a = 1 is stored in a temporary stack, and the program will not return immediately. When a = 2 is executed, the value of a is only overwritten, but the value returned in the temporary stack is not updated . If the value of a is output in finally, it is the overwritten value.

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

    public static int method(){
        int a = 0;
        try {
            a = 1;
            return a;
        }finally {
            a = 2;
            return a;
        }
    }
}
/**
output: 2
*/

        There is also a return in finally. At this time, the value in the temporary stack will be updated. After the execution of finally, the main program will be notified to return, that is, the value in the temporary station will be taken out. (So ​​you should know that it is best not to have return in finally, otherwise the program will exit early, and the return value is not the return value saved by try and catch.)


Summarize:

    1, finally will be executed, whether try..catch or not.

    2. If there is a return in try{ } before finally, it will execute the return first, save it, then execute the finally block, and finally execute the return.

    3. If there is a return in try{ } before finally, it will execute the return first, save the value, and then execute the return of the finally block, overwrite the value, and return.

(Of course, the catch block has the same return. The key is that the return is stored in the temporary stack and does not end immediately, but executes the finally block.)

Guess you like

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