JDK中的命名约定:java.lang.Throwable

时间:2012-08-24 04:24:54

标签: java

Java中的所有接口(如Serializable, Cloneable, Observable等)都以“-able”为后缀。但是,java.lang.Throwable不是接口而是类。

我理解java.lang.Throwable的用法,但我无法理解为什么以这种方式命名。这种异常是否有特定的原因?

2 个答案:

答案 0 :(得分:3)

与James Gosling的访谈lost to the dustbins of the internet,Sun的前副总裁和Java的主要架构师解释了为什么决定使Throwable成为一个类而不是一个接口。主要原因是因为需要跟踪状态

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.

答案 1 :(得分:0)

  

Throwable类是Java语言中所有错误和异常的超类。只有作为此类(或其子类之一)的实例的对象才被Java虚拟机抛出,或者可以被Java throw语句抛出。类似地,只有这个类或其子类之一可以是catch子句中的参数类型。

它包含所有可以抛出的 ,就像接口/抽象类那样。我想这应该是具有-able后缀的逻辑。虽然这不是一个论点......一般来说,你不应该假设以able结尾的任何东西都是一个接口。

<强>更新
现实生活中的另一个例子是我的一个项目...我必须创建一个(抽象)超类,其子类可以被缓存(在MemcacheD中)。它抽象了添加,删除,更新缓存所需的所有逻辑。什么是好名字?我把它命名为Cacheable。这个想法是,如果Cacheable它将被缓存。

所以,它只是语义 - 与命名模式无关。这里给出了唯一的命名模式:Java Naming Convention