Different ways to print exception messages in Java


Following are the different ways to handle exception messages in Java.

  • Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred.

    catch(Exception e) {    
       e.printStackTrace();
    }
    
  • Using toString() method − It prints the name and description of the exception.

    catch(Exception e) {    
       System.out.println(e.toString());
    }
    
  • Using getMessage() method − Mostly used. It prints the description of the exception.

    catch(Exception e) {    
       System.out.println(e.getMessage());
    }
    

Example

import java.io.Serializable;

public class Tester implements Serializable, Cloneable {
   public static void main(String args[]) {
   
      try {
         int a = 0;
         int b = 10;
         int result = b/a;
         System.out.println(result);

      } catch(Exception e) {    
         System.out.println("toString(): "  + e.toString());
         System.out.println("getMessage(): " + e.getMessage());
         System.out.println("StackTrace: ");
         e.printStackTrace();
      }
   }
}

Output

toString(): java.lang.ArithmeticException: / by zero
getMessage(): / by zero
StackTrace: 
java.lang.ArithmeticException: / by zero
at Tester.main(Tester.java:8)
raja
Published on 13-Aug-2018 12:22:01
Advertisements