why is java.lang.Throwable a class?

后端 未结 4 1290
鱼传尺愫
鱼传尺愫 2021-01-31 08:25

In java adjectives ending in -able are interfaces Serializable, Comparable etc... So why is Throwable a class? Wouldn\'t exception handlin

4条回答
  •  生来不讨喜
    2021-01-31 08:49

    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.

提交回复
热议问题