Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

exception handling - why is java.lang.Throwable a class?

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();

question from:https://stackoverflow.com/questions/2890311/why-is-java-lang-throwable-a-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...