why isn't java.lang.Throwable an abstract class?

社会主义新天地 提交于 2019-12-24 11:53:19

问题


Possible duplicate: why-is-java-lang-throwable-a-class

Hi! I doesn't understand why Throwable isn't abstract class. I see only one use case for these: in logging systems for figure out call hierarchy. But it can be some static method for this or other class. So, why?)

Thanks.

upd

from java.util.logging.LogRecord

// Get the stack trace.
StackTraceElement stack[] = (new Throwable()).getStackTrace();

Why it can't be Throwable.getStackTrace(); or as in java.lang.Thread

(new Exception()).getStackTrace();

In this way we can avoid throw new Throwable();

upd2 from javadoc

The Throwable class is the superclass of all errors and exceptions in the Java language.

So, as a superclass it should be abstract, imho. Using it for getting stacktrace isn't good case by this definition.


回答1:


I doesn't understand why Throwable isn't abstract class.

The answer is clearly stated here.

Why it can't be Throwable.getStackTrace(); or as in java.lang.Thread

Quite simply, the getStackTrace() calls the getOurStackTrace() method which is non-static. If getStackTrace() was static, so should getOurStackTrace(). This won't happen as printStackTrace() method uses the getOurStackTrace(). This is elaborated in the JavaDoc:

Provides programmatic access to the stack trace information printed by printStackTrace().

Source for java.lang.Throwable:

 public StackTraceElement[] getStackTrace() {
        return (StackTraceElement[]) getOurStackTrace().clone();
    }

Also, if you read the code of getOurStackTrace() method, you'll see it calls the following method:

private native int getStackTraceDepth();

As far as I know, native cannot be static (I may be wrong).




回答2:


I use it quite often for logging, so I am glad it isn't abstract. There is a method to get the call stack, Thread.currentThread().getStackTrace() but this returns a StackTraceElement[] which isn't very useful for logging.

EDIT:

StackTraceElement[] stes = Thread.currentThread().getStackTrace();  

Note: this method also works to get a stack trace of another thread which can be handy.



来源:https://stackoverflow.com/questions/4306214/why-isnt-java-lang-throwable-an-abstract-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!