1

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.

4

2 に答える 2

3

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).

于 2010-11-29T17:55:21.400 に答える
1

ロギングによく使うので、抽象的ではなくて良かったです。呼び出しスタックを取得するメソッドThread.currentThread()。getStackTrace()がありますが、これはStackTraceElement []を返しますが、これはロギングにはあまり役立ちません。

編集:

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

注:このメソッドは、便利な別のスレッドのスタックトレースを取得するためにも機能します。

于 2010-11-29T17:25:06.153 に答える