How to find originating class name where exception was thrown?
Give a simple reference to a Throwable
object. I want to just find out what the original class where 开发者_开发技巧this was thrown. I no longer am inside this class so all I have is a Throwable
object that was passed in from somewhere.
Use the GetStackTrace
property of Throwable
to retreive getClassName()
.
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/StackTraceElement.html
for (StackTraceElement ste : myThrowableObject.getStackTrace())
{
System.out.println(ste.getClassName());
}
This will print all classes involved.
Have you tried GetStackTrace() on your Throwable object?
Use the GetStackTrace( ) to retrieve the class name.
Provides programmatic access to the stack trace information printed by printStackTrace().
The stack trace will show the exception, but the exception may also have a cause, and so on.
The originating class is most likely the first stack trace element in the last cause, so you might want alter the collection logic according to your needs.
Here is how you can collect all involved classes in order of appearance.
Exception e = getTheException();
Set<String> classNames = new LinkedHashSet<>();
Throwable cause = e;
while (cause != null) {
Stream.of(cause.getStackTrace()).forEach(element-> classNames.add(element.getClassName());
cause = cause.getCause();
}
精彩评论