Methods to print exception information


There are 3 methods to print the exception information
toString() method/ reference
printStackTrace() method
getMessage() method

toString()/ reference

Print exception information using public String toString() or reference varaible. If we print reference directly then internally toString() will call. 


package com.exceptions;
public class Test {
       public static void main(String[] args) {
              try{         
              System.out.println(10/0);
              }
              catch(ArithmeticException ae){
                     System.out.println(ae);
                     //or
                     System.out.println(ae.toString());
              }            
       }
}


Output: print exception class : description


java.lang.ArithmeticException: / by zero


printStackTrace()

public void printStackTrace() method is available in java.lang.Throwable class to print exception information.


package com.exceptions;
public class Test {
       public static void main(String[] args) {
              try{         
              System.out.println(10/0);
              }
              catch(ArithmeticException ae){                 
                     ae.printStackTrace();
              }            
       }
}


Output: print exception class : description
               Print stack trace


java.lang.ArithmeticException: / by zero
       at com.exceptions.Test.main(Test.java:5)


getMessage()

public String getMessage() method is available in java.lang.Throwable class to print exception information.


package com.exceptions;
public class Test { 
       public static void main(String[] args) {
              try{         
                     System.out.println(10/0);
                     }
                     catch(ArithmeticException ae){                 
                           System.out.println(ae.getMessage());
                     }     
       }     
}


Output: Print description only


/ by zero



No comments:

Post a Comment