2017-04-05 70 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()