2017-05-08 96 views
-2
public class TestExceptions extends Exception { 
    public static void main(String[] args) 
    { 
     String test = "no"; 
     try { 
      System.out.println("start try"); 
      doRisky("no"); 
      System.out.println("end try"); 
     } catch(ScaryException se) { 
      System.out.println("scaryexception"); 
     } finally { 
      System.out.println("finally") ; 
     } 

     System.out.println("end of main"); 
    } 
    static void doRisky(String test) throws ScaryException { 
     System.out.println("start risky"); 
     if ("yes".equals(test)) { 
      throw new ScaryException(); 
     } 
     System.out.println("end risky"); 
     return; 
    } 
} 

此代碼不起作用。錯誤:找不到符號。這是Head First Java Book的例子。在Java中創建自己的例外

如果我們將該類的名稱更改爲TestExceptions中的ScaryException,那麼它工作正常。爲什麼這樣? 是否有必要使類名與我們在自定義異常情況下拋出的異常相同。

+1

是的,是必要的。如果你想使用'TestExceptions',那麼改變這一行'throw new TestException();' –

+1

這裏是:*** ScaryException ***在你的JDK中? –

+0

您必須使用同一個名稱來定義類的定義以及您在何處使用它。這對於例外情況並不特別。這是編程基礎知識 – Jens

回答

1

ScaryException.java

public class ScaryException extends Exception { 

     public ScaryException(String exceptionMsg){  
      System.out.println("in ScrayException: " +exceptionMsg); 
     } 
    } 

Main.java

public class Main { 

    public static void main(String[] args) { 
    String test = "no"; 
    try { 
     System.out.println("start try"); 
     doRisky("yes"); 
     System.out.println("end try"); 
     } 
    catch(ScaryException se) {   
     System.out.println("in catch"); 
     } 
    finally { 
     System.out.println("finally") ; 
     } 
    System.out.println("end of main"); 

    } 

    static void doRisky(String test) throws ScaryException { 
     System.out.println("start risky"); 
     if ("yes".equals(test)) { 
      throw new ScaryException("Scary Exception thrown from doRisky"); 
      } 
     System.out.println("end risky"); 
     return; 
} 

} 

可能這個例子將清楚地爲您服務。

是的,自定義Exception類和java文件的名稱應該相同。通過編寫擴展異常,您正在創建一個自定義異常。因此,在您的示例中,您正在創建TestExceptions,但試圖拋出不存在的ScaryExceptions。

0

是否有必要在類名相同的例外,我們 扔在自定義異常的情況下,

是的,這是必要的。

如果你想使用TestException,然後改變這一行throw new TestException();

您可以從Java Custom Exception

0

獲得更多的例子似乎你的假設是正確的。要麼應該有一個單獨的Exception類名爲ScaryException,您錯過了要添加的名稱,或者該名稱應該是ScaryException而不是TestExceptions。由於TestExceptions擴展了Exception,後者將是這種情況。