简体   繁体   English

使我自己成为Java的例外

[英]Make my own exceptions Java

I try to make my own exceptions in Java. 我尝试在Java中创建自己的异常。

I have a parent class like : 我有一个像这样的家长班:

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

and two children classes like : 还有两个子类,如:

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

I call it like that : 我这样称呼它:

in the main : 在主要方面:

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

and in my method : 和我的方法:

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

and Starter : 和入门:

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

I specify that i=0 for the tests. 我将测试指定为i = 0。

The probleme is that my exception in never throws. 问题是我的例外永不抛出。 Is there something wrong ? 有什么不对 ?

Thanks for helping me. 谢谢你帮我

Like @Berger also mensions in a comment: instead of e.getMessage() do either: 像@Berger一样,也要在注释中e.getMessage() :代替e.getMessage()执行以下任一操作:

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

or 要么

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

If that still not prints anything please provide more code where your i comes from so we can check why the error is not thrown. 如果仍然无法打印任何内容,请提供您i的更多代码,以便我们检查为什么未引发错误。

This here is not correct and is the reason why you see nothing when the exception is thrown 这是不正确的,这是引发异常时什么都看不到的原因

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

e.getMessage() returns a String and that is just getting lost in the stack e.getMessage() 返回一个字符串,并且该字符串刚刚在堆栈中丢失

Do instead: 改为:

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

in the catch 抓住

or just call e.printStackTrace() 或仅调用e.printStackTrace()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM