Usually write Java code, want to see the exception information thrown to find out the specific anomaly, we often use exception.tostring () or exception.getmessage () to get the exception information, and then print it to the console, But this information can only tell us the exception itself, and it's not ideal for us to find the anomaly, so we'll use the Exception.printstacktrace () method so we can output very detailed exception information at the console. It can even be traced to the first few lines of the class where the exception occurred, which is very useful to us. But sometimes we just want to get these stacktrace data and show it in other ways (not consoles, like web pages or GUIs), and that's the article. Recall that the original log tool log4, WebLogic server, There are webshpere servers and so on seem to be able to get this information, so first directly in the exception class to find there is no direct way to return this information, see Getstacktrace () method returns a collection of Stacktraceelement objects (why didn't you notice it?) ), flip the JDK, and look at the methods provided by the Stacktraceelement class (
|
String |
GetFileName () Returns the name of the source file containing the execution point represented by this stack trace element. |
Int |
Getlinenumber () Returns the line number of the "source line containing" execution point represented by this stack trace element. |
String |
Getmethodname () Returns the name of the method containing the execution point represented by this stack trace element. |
Int |
hashcode () Returns a hash code value for this stack trace element. |
Boolean |
Isnativemethod () Returns true if the method containing the execution point represented by this stack trace element are a native method. |
String |
toString () |
Yes, that's him, write a piece of code to test the first:
public static void Main (string[] args) {
try{
byte[] a=args[0].getbytes ();
} catch (Exception ex) {
ex.printstacktrace ();
Stacktraceelement [] Messages=ex.getstacktrace ();
int length=messages.length;
for (int i=0;i<length;i++) {
System.out.println ("ClassName:" +messages[i].getclassname ());
System.out.println ("GetFileName:" +messages[i].getfilename ());
System.out.println ("Getlinenumber:" +messages[i].getlinenumber ());
System.out.println ("Getmethodname:" +messages[i].getmethodname ());
System.out.println ("toString:" +messages[i].tostring ());}}}
Ok, the secret has been found, so that's what happened.
The above is transferred from: http://blog.csdn.net/haiquan968/article/details/4619737
Here's a way to get an exception detail.
Public String Getexceptiondetail (Exception e) {
StringBuffer stringbuffer = new StringBuffer (e.tostring () + "\ n"); c1/>stacktraceelement[] messages = E.getstacktrace ();
int length = Messages.length;
for (int i = 0; i < length; i++) {
stringbuffer.append ("\ T" +messages[i].tostring () + "\ n");
}
return stringbuffer.tostring ();
}