为什么是java.lang.Throwable一个类? [英] why is java.lang.Throwable a class?

查看:221
本文介绍了为什么是java.lang.Throwable一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以-able为结尾的java形容词是接口可序列化可比较等...所以为什么 Throwable 一个类?如果 Throwable 是一个接口,那么异常处理是否容易? (编辑:例如异常类不需要扩展Exception / RuntimeException。)



显然,现在更改它是一个问题。但是可以抽象吗?不会避免的糟糕做法抛出新的Throwable();

解决方案

那么为什么Throwable是一个课程?


我可以想到两个原因:


  1. 异常有状态。特别是消息,原因和堆栈跟踪。

  2. JVM更容易实现高效的catch块。类别层次结构检查比接口检查便宜。




不会异常处理更容易
如果Throwable是一个接口?


无论异常是类还是接口,异常处理都是一个难题。我实际上怀疑,如果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();

解决方案

So why is Throwable a class?

I can think of two reasons:

  1. Exceptions have state. In particular, message, cause, and stack trace.
  2. It is easier for the JVM to implement efficient catch blocks. Class hierarchy checks are cheaper than interface checks.

Wouldn't exception handling be easier if Throwable were an interface?

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.

But could it be made abstract?

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一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆