2017-04-05 74 views
1

我嘗試在Java中創建自己的例外。製作我自己的例外Java

我有一個父類,如:

public class PException extends Exception { 
    public PException(String msg) { 
     super(msg); 
    } 
} 

和兩個孩子類,如:

public class noGoalException extends PException { 
    public noGoalException(){ 
     super("No Goal"); 
    } 
} 

我把它叫做這樣的:

主:

try { 
    Starter s = new Starter("res/init"); 
} catch (PException e) { 
    e.getMessage(); 
} 

和m ÿ方法:

private void parseGoals() throws PException { 
    [...] 
    if (i == 0) { 
     throw new noGoalException(); 
    } 
} 

和Starter:

public Starter(String fileName) throws GPException { 
    [...] 
    parseGoals(); 
} 

我指定I = 0的測試。

問題是我的例外從未拋出。有什麼不對 ?

感謝您的幫助。

+2

請注意,'e.getMessage();'本身不會打印任何東西,請嘗試'e.printStackTrace()'。 – Berger

+2

你必須使用'System.out.println(e.getMessage());'而不是'e.getMessage()' –

+0

@Kayaman yes對於mmy測試,我= 0 – iAmoric

回答

1

像@Berger也評論mensions: 代替e.getMessage()請執行:

try { 
    Starter s = new Starter("res/init"); 
} catch (PException e) { 
    System.out.println(e.getMessage()); 
} 

try { 
    Starter s = new Starter("res/init"); 
} catch (PException e) { 
    e.printStackTrace(); 
} 

如果仍然不打印任何東西,請提供更多的代碼,在您我來自所以我們可以檢查爲什麼不會拋出錯誤。

+0

哦,是的,這是我的錯我忘了System.out.println()..但即使使用e.printStackTrace(),也沒有任何反應 – iAmoric

+0

它適用於System.out.println(e.getMessage())。 – iAmoric

0

在這裏,這是不正確的,這就是爲什麼你看到什麼時候拋出異常

try { 
    Starter s = new Starter("res/init"); 
} catch (PException e) { 
    e.getMessage(); 
} 

e.getMessage()returns a String和纔剛剛在堆棧中丟失

做,而不是原因:

System.out.println(e.getMessage()); 

in the catch

或只是打電話e.printStackTrace()