●假設二個Exception沒有繼承關係,但其內處理方式一模一樣,如何解決?

●JDK7提供catch multiple exception功能,可能有效減少重複的程式碼。

public class MyAutoCloseable implements java.lang.AutoCloseable {
    
    public void f1(){
        throw new IllegalArgumentException("F1 Exception");
    }
    
    @Override
    public void close() throws Exception {
        throw new IllegalArgumentException("Close Exception");
    }
}

 

 

    public static void main(String[] args) {
         
        try (MyAutoCloseable x = new MyAutoCloseable()){
            x.f1();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
     }

 

●在專案上,盡量不要catch上層父類別,原則上還是要catch個別子類別,以利用發出精準之錯誤訊息。

創作者介紹
創作者 翔の學習淺談 的頭像
淺翔

翔の學習淺談

淺翔 發表在 痞客邦 留言(0) 人氣( 60 )