Diagram of the one or three-person relationship:
Second, demo 1, Printstacktrace () Demo:
public class Test
{
public int div (int a, int b)
{
Try
{
return a/b;
} catch (Exception e)
{
E.printstacktrace ();
}
return 0;
}
public static void Main (string[] args)
{
Test test = new test ();
Test.div (3, 0);
}
}
Printing results:
E.printstacktrace () prints out an exception, but it also shows deeper invocation information. It is a layer-by-layer investigation, and eventually goes back to Com.glxt.....main (main function).
It is suitable for debugging purposes.
2. ToString () Demo
public class Test
{
public int div (int a, int b)
{
Try
{
return a/b;
} catch (Exception e)
{
System.out.println (E.tostring ());
}
return 0;
}
public static void Main (string[] args)
{
Test test = new test ();
Test.div (3, 0);
}
}
Printing results:
3. GetMessage () Demo
public class Test
{
public int div (int a, int b)
{
Try
{
return a/b;
} catch (Exception e)
{
System.out.println (E.getmessage ());
}
return 0;
}
public static void Main (string[] args)
{
Test test = new test ();
Test.div (3, 0);
}
}
Printing results:
Note: How to get the contents of E.printstacktrace ()
E.printstacktrace () is usually printed on the console, but sometimes it's not easy to see the contents of the stack when the program is online, as there are many or very few things printed in the production environment, and sometimes it is not possible to see them directly, and this time we need to record them. such as logging into the database, the following methods can be fully logged.
public static void Main (string[] args) {
try {
String AA = "";
System.out.println (Aa.substring (3));
} catch (Exception e) {
E.printstacktrace ();
StringWriter SW = new StringWriter ();
E.printstacktrace (New PrintWriter (SW, True));
String str = sw.tostring ();
System.out.println ("==========");
System.out.println (str);
}
}
The effect of printing is as follows:
Java.lang.StringIndexOutOfBoundsException:String index out of range: 3
At java.lang.String.substring (Unknown Source)
At java.lang.String.substring (Unknown Source)
At Getc.main (getc.java:16)
==========
Java.lang.StringIndexOutOfBoundsException:String index out of range: 3
At java.lang.String.substring (Unknown Source)
At java.lang.String.substring (Unknown Source)
At Getc.main (getc.java:16)
Differences between Printstacktrace (), toString (), GetMessage () in Java