Linkedin Java 檢定題庫 try catch 流程


Posted by c9103205 on 2021-07-02

public static void main(String[] args) {
    try {
        System.out.println("A");
        badMethod();
        System.out.println("B");
    } catch (Exception ex) {
        System.out.println("C");
    } finally {
        System.out.println("D");
    }
}
public static void badMethod() {
    throw new Error();
}
  1. A, B, and D
  2. A, C, and D
  3. C and D
  4. A and D

answer : 4
解析:
本題首先必須明白 Exception 與 Error的差別。
你可點 這裡

走到 badMethod() 這個method後
直接 throw new Error();
注意 Error != Exception
而這裡的catch只會捕捉Exception的情況
故不會印出"C"
最後finally則是不管怎樣都會執行
所以最終答案是 A D
實際程式跑出來的結果如下

A
D
Exception in thread "main" java.lang.Error
    at Main.badMethod(scratch.java:21)
    at Main.main(scratch.java:12)

#linkedin #java







Related Posts

2048 專案

2048 專案

Day 149

Day 149

JS註冊組|決策與迴圈|JavaScript&jQuery網站互動設計程式進化之道

JS註冊組|決策與迴圈|JavaScript&jQuery網站互動設計程式進化之道


Comments