Friday, March 15, 2019

printStackTrace Examples

Java Throwable printStackTrace() method
The printStackTrace() method of Java Throwble class is used to print the Throwable along with other details like classname and line number where the exception occurred.

Syntax


  1. public void printStackTrace()  

Example 1


  1. import java.lang.Throwable;  
  2. public class ThrowablePrintStackTraceExample1 {  
  3.     public static void main(String[] args) throws Throwable {  
  4.    try{  
  5.        int i=4/0;  
  6.    }catch(Throwable e){  
  7.        e.printStackTrace();  
  8.        System.err.println("Cause : "+e.getCause());  
  9.    }  
  10. }  
  11. }  
Output:

java.lang.ArithmeticException: / by zero
 at ThrowablePrintStackTrace.main(ThrowablePrintStackTrace.java:5)
Cause : null


Example 2

  1. public class ThrowablePrintStackTraceExample2 {  
  2.     public static void main(String[] args)throws Throwable {  
  3.         try{  
  4.             exceptionTest();  
  5.         }catch(Throwable t){  
  6.             t.printStackTrace();  
  7.         }  
  8. }  
  9.     public static void exceptionTest() throws Exception{  
  10.         System.out.println("Inside exceptionTest() method");  
  11.         throw new Exception("Throwing localized message!");  
  12.     }  
  13. }  

Output:
Inside exceptionTest() method
java.lang.Exception: Throwing localized message!
 at ThrowablePrintStackTraceExample2.exceptionTest(ThrowablePrintStackTraceExample2.java:11)
 at ThrowablePrintStackTraceExample2.main(ThrowablePrintStackTraceExample2.java:4)

No comments:

Post a Comment