Custom Java exceptions

Software

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.

Author bio and support

Me!

Ruben Schade is a technical writer and infrastructure architect in Sydney, Australia who refers to himself in the third person. Hi!

The site is powered by Hugo, FreeBSD, and OpenZFS on OrionVM, everyone’s favourite bespoke cloud infrastructure provider.

If you found this post helpful or entertaining, you can shout me a coffee or send a comment. Thanks ☺️.