Search code examples
javaexceptionclass-design

why is java.lang.Throwable a class?


In java adjectives ending in -able are interfaces Serializable, Comparable etc... So why is Throwable a class? Wouldn't exception handling be easier if Throwable were an interface? (Edit: e.g. Exception classes don't need to extend Exception/RuntimeException.)

Obviously, changing it now is out the question. But could it be made abstract? Wouldn't that avoid the bad practice of throw new Throwable();


Solution

  • So why is Throwable a class?

    I can think of two reasons:

    1. Exceptions have state. In particular, message, cause, and stack trace.
    2. It is easier for the JVM to implement efficient catch blocks. Class hierarchy checks are cheaper than interface checks.

    Wouldn't exception handling be easier if Throwable were an interface?

    Exception handling is a hard topic regardless of whether exceptions are classes or interfaces. I actually suspect it would make it harder on Java programmers if they have to order their catch blocks based on arbitrary interfaces rather than on class hierarchies.

    But could it be made abstract?

    In theory, yes. In practice, no. Too much code depends on being able to create an instance of Throwable in order to call getStackTrace.