```java public class ExampleTryCatch4 { public static void main(String[] args) { /* * 這篇討論 finally。 * * 當 try catch 有附上 finally 的區塊時, * 在大部分的狀態下會執行 finally 區塊內的程式。 */ File file = new File(""); try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } finally { //區塊 finally 是可選擇的語法,並不一定要加入使用, //若選擇不加入時,會像下方標注區塊的樣子 System.out.println("show me!"); } // File file = new File(""); // try { // file.createNewFile(); // } catch (IOException e) { // e.printStackTrace(); // } //狀況二 try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); //若錯誤發生,這邊的 return 將會執行,並中斷程式。 return; } finally { //雖然已經中斷了整個程式,但 show me again 還是會執行。 System.out.println("show me again!"); } //狀況三 try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); //若錯誤發生,這邊的 System.exit(0) 將會執行,並中斷及離開程式。 System.exit(0); } finally { //已經離開程式,所以這邊的 show me last time 就不會執行。 System.out.println("show me last time!"); } try { test1(); // 因為內部的錯誤往外丟,所以這邊要 try catch } catch (IOException e) { System.out.println( "Error from OUTSIDE method : " + e.getMessage()); e.printStackTrace(); } /* * 因為 finally 一定會執行,因此即使 try block 內已經 return 了值, * 但 finally 還是會把結果蓋過去。 */ System.out.println(test2()); } public static void test1() throws IOException { try { File file = new File(""); file.createNewFile(); } catch (IOException e) { // 內部的錯誤選擇往外丟 throw new IOException("Error from INSIDE method"); //return; //這邊如果選擇跑 return 結果仍然會差不多, //只差在沒有 throw Exception 到外層 } finally { System.out.println("show me from test1!"); //一定會執行 } System.out.println("test1 fin"); //不會執行到這邊 } @SuppressWarnings("finally") public static int test2() { try { return 1; } catch (Exception e) { return 2; } finally { return 3; } } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up