问题描述
在以-able为结尾的java形容词是接口可序列化
,可比较
等...所以为什么 Throwable
一个类?如果 Throwable
是一个接口,那么异常处理是否容易? (编辑:例如异常类不需要扩展Exception / RuntimeException。)
显然,现在更改它是一个问题。但是可以抽象吗?不会避免的糟糕做法抛出新的Throwable()
;
那么为什么Throwable是一个课程?
我可以想到两个原因:
- 异常有状态。特别是消息,原因和堆栈跟踪。
- JVM更容易实现高效的catch块。类别层次结构检查比接口检查便宜。
无论异常是类还是接口,异常处理都是一个难题。我实际上怀疑,如果Java程序员必须基于任意接口而不是在类层次结构上排序它们的catch块,那么它会更加困难。
理论上说是的。实际上没有。代码太多取决于是否可以创建一个Throwable的实例来调用getStackTrace。
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()
;
I can think of two reasons:
- Exceptions have state. In particular, message, cause, and stack trace.
- It is easier for the JVM to implement efficient catch blocks. Class hierarchy checks are cheaper than interface checks.
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.
这篇关于为什么是java.lang.Throwable一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!