2013-05-14 134 views
0

我試圖創建一個方法f1(x),當x等於5時拋出異常。之後,我將嘗試從另一個方法f2()調用該方法來調用該異常。然後我必須通過呼叫f1(x+1)來恢復f2()。我嘗試編碼的東西,但我卡住了。下面是代碼:創建自定義異常

public class FiveException extends Exception { 

public void f1(int x) throws FiveException { 
    if (x == 5) { 
     throw new FiveException(); 
    } 
} 

public void f2() { 
    int x = 5; 
    try { 
     f1(x); 
    }catch (FiveException e) { 
     System.out.println("x is 5"); 
    } 

} 


public static void main(String[] args) { 
    FiveException x5 = new FiveException(); 
    x5.f2(); 
} 

} 

print語句的工作,但我不知道如何調用f(x+1)。對於如何解決這個問題和任何技巧來編寫例外有幫助。

+0

引發異常的代碼不應位於FiveException類中。 –

+0

你想在哪裏調用'f1(x + 1)'?在哪個方法裏面? – fhelwanger

+0

@fhelwanger我試着在'f2()'中的catch語句下調用'f1(x + 1)',但它給了我一個錯誤。 – blutuu

回答

1

因爲f1引發FiveException,無論您撥打f1,您必須捕獲該異常或將其引發至調用引發異常的方法的方法。例如:

public static void main(String[] args) throws FiveException { 
    FiveException x5 = new FiveException(); 
    x5.f1(1); 
} 

或者:

public static void main(String[] args) { 
    FiveException x5 = new FiveException(); 

    try { 
     x5.f1(1); 
    } catch (FiveException e) { 
     e.printStackTrace(); 
    } 
} 

但你的代碼混淆......通常,它不是異常類,拋出自己,你有拋出異常類其他類。

如果它被catch語句中調用,你必須與另一個try-catch圍繞着它,「造成內部catch的代碼是不受保護的,就像這樣:

public void f2() { 
    int x = 5; 
    try { 
     f1(x); 
    }catch (FiveException e) { 
     System.out.println("x is 5"); 
     try { 
      f1(x + 1); 
     } catch (FiveException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

但是這個代碼是醜陋的,你可以請寫下以下內容:

public void f2() { 
    int x = 5; 
    fProtected(x); 
    fProtected(x + 1); 
} 

private void fProtected(int x) { 
    try { 
     f1(x); 
    }catch (FiveException e) { 
     System.out.println("x is 5"); 
    } 
} 
+0

有趣。我會研究這一點,並會看看這是否是我正在尋找的所需代碼。 – blutuu