why is java.lang.Throwable a class?

后端 未结 4 1289
鱼传尺愫
鱼传尺愫 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.

    0 讨论(0)
  • 2021-01-31 09:02

    well Hashtable is also a concrete class! Something that can be hashted.

    and what is Cloneable? it is not a correct English word.

    0 讨论(0)
  • 2021-01-31 09:06

    Here's how James Gosling explained his decision:

    Java Developer Connection Program: Why is Throwable not an interface? The name kind of suggests it should have been. Being able to catch for types, that is, something like try {} catch (<some interface or class>), instead of only classes. That would make [the] Java [programming language] much more flexible.

    James Gosling: The reason that the Throwable and the rest of those guys are not interfaces is because we decided, or I decided fairly early on. I decided that I wanted to have some state associated with every exception that gets thrown. And you can't do that with interfaces; you can only do that with classes. The state that's there is basically standard. There's a message, there's a snapshot, stuff like that — that's always there. and also, if you make Throwable an interface the temptation is to assign, to make any old object be a Throwable thing. It feels stylistically that throwing general objects is probably a bad idea, that the things you want to throw really ought to be things that are intended to be exceptions that really capture the nature of the exception and what went on. They're not just general data structures.

    References

    • Wayback Machine snapshot/About Java Technology: An Interview with James Gosling
    0 讨论(0)
  • 2021-01-31 09:10

    FYI

    You can not use

    void doSomething() throws Serializable
    

    but you can use generics!

    <T extends Exception & Serializable> doSomething() throws T
    

    Regards

    0 讨论(0)
提交回复
热议问题