Exception and Throwable Java classes

Software

Classic Java logo

A few weeks ago I talked about how you can throw custom exceptions in Java which can be extremely useful for dealing with certain events. The problem a few people raised with my example though was my use of Throwable instead of Exception, so this afternoon I wanted to briefly explore the error in my ways!

While using Throwable in the context of throwing custom error messages technically works, the Exception class inherits directly from Throwable and is on the same level as the exceptions Java throws itself (surprising given the name!) which makes it a more correct choice.

The reason why my lecturer and I were using Throwable instead of Exception was because we wanted access to the printStackTrace() method which provides valuable feedback. It turns out given Exception is a subclass of Throwable it also implements it! Sometimes the most obvious things are the most elusive.

To test that Exception did indeed implement the printStackTrace() method I wrote a basic Java application called Nonsense in which I created custom Throwable and Exception errors, triggered them with some dummy methods and finally handled them in try and catch blocks which printed the results.

public class Nonsense {
  public static void main(String[] args) {
    try { testThrowable(); }
    catch(throwableError e) { e.printStackTrace(); }
    try { testException(); }
    catch(exceptionError e) { e.printStackTrace(); }
  }
  static void testThrowable() throws throwableError {
    throw new throwableError();
  }
  static void testException() throws exceptionError {
    throw new exceptionError();
  }
}
class throwableError extends Throwable {
  public throwableError() {
    super("Whoops! THROWABLE error!");
  }
}
class exceptionErr extends Exception {
  public exceptionError() {
    super("Whoops! EXCEPTION error!");
  }
}

Aside from the line numbers the printStackTrace() method reports in both, the output is identical. Lesson learned, if I want to specifically throw my own Exception, I'll use the Exception class!

I restrained myself, I didn't end up making the lame comment that "I take exception to all these Exceptions!" until the last line. I'm proud of myself.

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 ☺️.