Try{}catch (Exception e) {}finally{}
Java exception handling is common in programming, where statements that may throw exceptions are placed in try{}, and if an exception is thrown, the statement after the exception statement that is thrown in try{} is no longer executed. catch (Exception e) {} Fetches the exception and processes it, and if there is no exception, the statement in the catch is not executed. finally{} mainly in the aftermath of the work, such as resource recovery. The statement in finally executes regardless of whether an exception is thrown. The statement in finally will be called before the exception capture mechanism exits.
Let's take a look at three simple examples:
Example 1,
public static void Test1 () {try {httpurlconnection connection = (httpurlconnection) New URL (""). OpenConnection (); System.out.println ("Try");} catch (Exception e) {System.out.println ("Exception");} finally {System.out.println ("finally");} System.out.println ("End");} /* Output: exception finally end */
Example 2,
public static void Test1 () {try {httpurlconnection connection = (httpurlconnection) New URL ("http://www.baidu.com"). OpenConnection (); System.out.println ("Try");} catch (Exception e) {System.out.println ("Exception");} finally {System.out.println ("finally");} System.out.println ("End");} /* Output: try finally end */
Example 3,
public static void Test1 () {try {httpurlconnection connection = (httpurlconnection) New URL ("http://www.baidu.com"). OpenConnection (); System.out.println ("Try"); return;} catch (Exception e) {System.out.println ("Exception");} finally {System.out.println ("finally");} System.out.println ("End");} /* Output: try finally */
First, the first example, httpurlconnection connection = (httpurlconnection) New URL (""). OpenConnection (); URL address is empty, throws an exception, the statement after the try is not executing and jumps directly to catch{}, so there is no "try" in the output.
In the second example, the URL is available, no exception is thrown, so the statement in catch{} does not execute, so there is no "catch" in the output.
In Example 3, the catch is not executed because no exception is thrown. Because a return is already in the try, the subsequent statement is not executed. Before the return, follow the exception capture mechanism, and the finally will be called before exiting.
Java Try Catch finally