Java 中的所有接口(interface),如 Serialized、Cloneable、Observable
等,都带有“-able”后缀。但是,java.lang.Throwable
不是一个接口(interface),而是一个类。
我理解 java.lang.Throwable 的用法,但我无法理解为什么它以这种方式命名。这种异常现象有具体原因吗?
最佳答案
采访lost to the dustbins of the internet Sun 前副总裁兼 Java 主要架构师 James Gosling 解释了为什么决定将 Throwable 设为类而不是接口(interface)。主要原因是 Throwables 需要跟踪状态:
JDC: 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.
JG: 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.
关于java - JDK 中的命名约定 : java. lang.Throwable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12103124/