为什么 java.lang.Throwable 是一个类?
在 java 中,以 -able 结尾的形容词是接口 Serialized
、Comparable
等...那么为什么 Throwable
是一个类呢?如果 Throwable
是一个接口,异常处理不是更容易吗? (编辑:例如,Exception 类不需要扩展 Exception/RuntimeException。)
显然,现在更改它是不可能的。但它能变得抽象吗?这不是可以避免 抛出 new Throwable()
; 的不良做法吗?
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()
;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
詹姆斯·高斯林是这样解释他的决定的:
参考文献
Here's how James Gosling explained his decision:
References
我可以想到两个原因:
无论异常是类还是接口,异常处理都是一个难题。我实际上怀疑,如果 Java 程序员必须根据任意接口而不是类层次结构来排序 catch 块,那么这会让他们变得更加困难。
理论上是的。实际上,没有。太多代码依赖于能够创建 Throwable 实例来调用 getStackTrace。
I can think of two reasons:
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.
In theory, yes. In practice, no. Too much code depends on being able to create an instance of Throwable in order to call getStackTrace.
那么 Hashtable 也是一个具体的类!可以散列的东西。
什么是可克隆?这不是一个正确的英语单词。
well Hashtable is also a concrete class! Something that can be hashted.
and what is Cloneable? it is not a correct English word.
仅供参考,
您不能使用泛型
,但可以使用泛型!
问候
FYI
You can not use
but you can use generics!
Regards