
Well today in Java we learnt how to throw our own exceptions. Because Exception is an inherited object of Throwable rather than just a primitive or a pointer we can create our own Exception objects for circumstances where we want Java to treat an event in the same way as an error.
public class TrekError extends Throwable {
public TrekError() {
// pass to superclass (Throwable) constructor
super("Your logic is fatally flawed!");
}
}
public class TestTrekError {
public static void main(String[] args) throws TrekError {
boolean trekBetterThanWars = true;
if (trekBetterThanWars == false) {
throw new TrekError();
} else {
System.out.println("Live long and prosper!");
}
}
}
As I think back to programs I've written in the past in other languages this could have been quite useful! Do Ruby and Python offer similar capability?
The main question I had that I didn't have time to ask in the lecture though was what the "better" or more correct way to use this in Java is. Are there circumstances where you could use such a technique but it would be a cheap shortcut rather than writing robust code? I suspect for all the usefullness that could be derived from this, it could also be easily abused.
I have I am curious, why do you choose to extend Throwable?
This is a not a golden rule, but generally (in my experience anyway), custom exceptions extend from... Exception (surprise!)
Because not everything throwable are meant to be caught. That sounds strange, I know.
See Error http://java.sun.com/javase/7/docs/api/java/lang/Error.html VS Exception http://java.sun.com/javase/7/docs/api/java/lang/Exception.html
Dang typo. I need a Preview button!
Thanks for the clarification :). Our teacher expects us to specifically use Throwable instead of Exception, he gave us a reason which seemed legitimate at the time but I can't remember what it was. I'll ask him and put his answer here when I do. What you've said though makes perfect sense, there's no reason not to extend Exception instead.