1. Get the Java exception printstacktrace details
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 (
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 ());
}
}
}
2.
Import Java.io.PrintWriter;
Import Java.io.StringWriter;
public class Printwritertest {
public static void Main (string[] args) {
try{
Exception ex = new Exception ("AAA");
Throw ex;
}catch (Exception e) {
StringWriter SW = new StringWriter ();
E.printstacktrace (new PrintWriter (SW));
System.out.println ("*****=" +sw.getbuffer (). toString ());
}
}
}