當程式意外的出現錯誤時,若沒有適當的處理, 可能就會直接導致程式掛掉。 所以把可能發生的錯誤捕捉起來,就是 try catch 的作用。 ```java public class ExampleTryCatch { public static void main(String[] args) { /* * 情境一 * 下面前兩段程式都刻意製造成會產生 Exception 的狀態。 * 但也都使用了 try catch 包覆錯誤, * 所以即使發生了錯誤,程式也不會因此中斷。 */ System.out.println("situation1 start"); String str = "abc"; try { Integer.parseInt(str); } catch (NumberFormatException e) { e.printStackTrace(); } List<String> list = new ArrayList<>(); try { list.get(0); } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } /* * 在這邊刻意設定 catch 類型錯誤,若執行這段程式, * 將導致無法捕捉到 IndexOutOfBoundsException 引發的例外 * 因此程式將會中斷在這個部分。 */ // try { // list.get(0); // } catch (NullPointerException e) { // e.printStackTrace(); // } System.out.println("situation1 fin"); /* * 情境二 * 兩段程式同樣都蓄意造成產生 Exception 的狀態。 * 但這次 Integer.parseInt 這個功能就刻意不處理了 * * 此時就可以發現當 NumberFormatException 出現後, * 程式就中止在錯誤出現的地方了 */ System.out.println("situation2 start"); String str2 = "cde"; Integer.parseInt(str2); //以下的程式都不會運作,因為上方的 Exception 一旦出現就會中止程式 List<String> list2 = new ArrayList<>(); try { list2.get(0); } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } System.out.println("situation2 fin"); } } ```
×
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