Java如何使用finally塊來捕捉異常?

2019-10-16 22:29:16

在Java程式設計中,如何使用finally塊來捕捉異常?

此範例顯示如何使用finally塊來通過使用e.getMessage()捕獲執行時異常(Illegalargumentexception)。

package com.yiibai;

public class UseOfFinally {
    public static void main(String[] argv) {
        new UseOfFinally().doTheWork();
    }

    public void doTheWork() {
        Object o = null;
        for (int i = 0; i < 5; i++) {
            try {
                o = makeObj(i);
            } catch (IllegalArgumentException e) {
                System.err.println("Error: (" + e.getMessage() + ").");
                return;
            } finally {
                System.err.println("All done");
                if (o == null)
                    System.exit(0);
            }
            System.out.println(o);
        }
    }

    public Object makeObj(int type) throws IllegalArgumentException {
        if (type == 1)
            throw new IllegalArgumentException("Don't like type " + type);
        return new Object();
    }
}

上述程式碼範例將產生以下結果 -

All done
Error: (Don't like type 1).
All done
java.lang.Object@2a139a55

範例-2

以下是java中使用finally塊捕捉異常的另一個範例:

package com.yiibai;

public class UseOfFinally2 {
    public static void main(String[] args) {
        try {
            int data = 25 / 5;
            System.out.println(data);
        } catch (NullPointerException e) {
            System.out.println(e);
        } finally {
            System.out.println("finally block is always executed");
        }
        System.out.println("rest of the code...");
    }
}

上述程式碼範例將產生以下結果 -

5
finally block is always executed
rest of the code...