gpt4 book ai didi

java - 为什么 java.lang.Throwable 是一个类?

转载 作者:IT老高 更新时间:2023-10-28 20:47:54 26 4
gpt4 key购买 nike

在java中以-able结尾的形容词是接口(interface)SerializableComparable等等...那么为什么Throwable是一个类呢?如果 Throwable 是一个接口(interface),异常处理会不会更容易? (编辑:例如 Exception 类不需要扩展 Exception/RuntimeException。)

显然,现在改变它是不可能的。但它可以抽象吗?那岂不是避免了 throw new Throwable();

的坏习惯

最佳答案

詹姆斯·高斯林是这样解释他的决定的:

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.

引用文献

关于java - 为什么 java.lang.Throwable 是一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2890311/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com