Reputation: 1965
I try to make my own exceptions in 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.
The probleme is that my exception in never throws. Is there something wrong ?
Thanks for helping me.
Upvotes: 1
Views: 70
Reputation: 48258
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
Do instead:
System.out.println(e.getMessage());
in the catch
or just call e.printStackTrace()
Upvotes: 1
Reputation: 822
Like @Berger also mensions in a comment:
instead of e.getMessage()
do either:
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.
Upvotes: 1