Execution order of try, catch, finally in PHP

try {
     //Execute the logic, throw an exception if there is an exception (catch listens to the exception)
} catch (HttpException $e) {
     //Always monitor the exception thrown by the HttpException error class
} catch (Exception $e) {
     //Always monitor the exception thrown by the Exception error class
} finally {
     //Finally execute, regardless of whether an exception is thrown or not
}

The execution order of the code is: execute try first, run catch when an exception is detected, and catch will not be run if there is no exception, but both cases will be finally, and the return (refun) value in finally will override the try and catch return value, if there are die and exit in the previous statement, finally will not be executed.

The significance of finally is that it can handle operations such as cleaning up and recycling some resources.

    private int testReturn1() {
            int i = 1;
            try {
                i++;
                System.out.println("try:" + i);
                return i;
            } catch (Exception e) {
                i++;
                System.out.println("catch:" + i);
            } finally {
                i++;
                System.out.println("finally:" + i);
            }
            return i;
        }

When there is a return statement in the try-catch block, the return statement temporarily stores the variable value, and then executes the finally code block.

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish