Differences between printStackTrace (), toString (), and getMessage () in Java, and printstacktrace
1. Relationship between the three elements:
Ii. 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 );
}
}
Print result:
E. printStackTrace () Prints an exception, but it also displays more detailed call Information. It is an external investigation layer by layer, and will return to com. glxt ..... Main (main function ).
It is suitable for debugging.
2. toString () Demonstration
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 );
}
}
Print result:
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 );
}
}
Print result:
Note: how to obtain e. printStackTrace () Content
E. printStackTrace () is usually printed on the console. However, it is not easy to view the stack content when the program goes online. Many or few items are printed in the production environment, second, you may not be able to directly view the content. In this case, you need to record the content, for example, to the database. The following method can be fully recorded.
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 print effect 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)