今天要學習的是 Exceptions
public class Main { public static void main(String[] args) {
int x = 99;
int y = 0;
System.out.println(divide(x, y));
} private static int divide(int x, int y) {
return x / y;
}}
輸出結果:
Exception in thread “main” java.lang.ArithmeticException: / by zero
at Main.divide(Main.java:20)
at Main.main(Main.java:6)
可以看到程序報錯了
public class Main { public static void main(String[] args) {
int x = 99;
int y = 0;
System.out.println(divideOfLBYL(x, y));
System.out.println(divideOfEAFP(x, y));
} private static int divideOfLBYL(int x, int y) {
if (y != 0) {
return x / y;
} else {
return 0;
}
} private static int divideOfEAFP(int x, int y) {
try {
return x / y;
} catch (ArithmeticException e) {
return 0;
}
}
}
輸出結果:
0
0
這次有對錯誤進行處理,所以程序沒報錯
常見的有兩種設計思想
- LBYL: Look Before You Leap — 事先檢查
- EAFP: Easier to Ask for Forgiveness than Permission — 出錯了用例外事後補救
文章補充:
我自己則總結成
LBYL 就是設計者把心力花在前段,提前設想各種可能狀況,寫下各種條件判斷
EAFP 就是設計者認把心力花在後段,有可能出錯的地方讓 Catch 去處理就好
import java.util.Scanner;public class Main { public static void main(String[] args) {
int x = getInt();
System.out.println("x is " + x);
} private static int getInt() {
System.out.print("Please enter X: ");
Scanner s = new Scanner(System.in);
return s.nextInt();
}}
輸出結果:
Please enter X: 5
x is 5
但是如果不是輸入數字
輸出結果:
Please enter X: abc
Exception in thread “main” java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.getInt(Main.java:13)
at Main.main(Main.java:6)
import java.util.Scanner;public class Main { public static void main(String[] args) {
int x = getIntLBYL();
System.out.println("x is " + x);
} private static int getIntLBYL() {
Scanner s = new Scanner(System.in);
System.out.println("Please enter an integer");
if(s.hasNextInt()) {
return s.nextInt();
}
return 0;
}}
輸出結果:
Please enter an integer: 123456
x is 123456
若輸入非數字則會
輸出結果:
Please enter an integer: 123a
x is 0
import java.util.InputMismatchException;
import java.util.Scanner;public class Main { public static void main(String[] args) {
int x = getIntEAFP();
System.out.println("x is " + x);
} private static int getIntEAFP() {
Scanner s = new Scanner(System.in);
System.out.print("Please enter an integer: ");
try {
return s.nextInt();
} catch (InputMismatchException e) {
return 0;
}
}}
輸出結果:
Please enter an integer: 654321
x is 654321
若輸入非數字則會
輸出結果:
Please enter an integer: 65432a
x is 0
以上兩種方式都能順利運行
那麼到底哪一種比較好呢?
Tim 老師 :沒有哪一種一定比另一種好,各有優缺,實際上要看使用情境來決定
場景若是在讀寫檔案,用 try catch 寫起來就很方便直觀
場景若是在 Map 裡確認某組 Key 是否存在,那麼使用 LBYL 則比較合理了
直接 if 條件判斷就好了,若寫成 try 跟 catch 反而比較麻煩