Custom Java exceptions

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.


Imprint

This is one of about 5000 posts on Rubénerd. View the home page for the latest, or related posts also tagged with:

If you liked this post, feel free to buy me a coffee, leave me a comment on Twitter, or email me at weblog2017@rubenschade.com. Thanks :).