What are the differences between printStackTrace() method and getMessage() method in Java?

JavaObject Oriented ProgrammingProgramming

There are two ways to find the details of the exception, one is the printStackTrace() method and another is the getMessage() method.

printStackTrace() method

  • This is the method which is defined in java.lang.Throwable class and it is inherited into java.lang.Error class and java.lang.Exception class.
  • This method will display the name of the exception and nature of the message and line number where an exception has occurred.

Example

public class PrintStackTraceMethod {
   public static void main(String[] args) {
      try {
         int a[]= new int[5];
         a[5]=20;
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Output

java.lang.ArrayIndexOutOfBoundsException: 5
        at PrintStackTraceMethod.main(PrintStackTraceMethod.java:5)

getMessage() method

  • This is a method which is defined in java.lang.Throwable class and it is inherited into java.lang.Error and java.lang.Exception classes.
  • This method will display the only exception message.

Example

public class GetMessageMethod {
   public static void main(String[] args) {
      try {
         int x=1/0;
      } catch (Exception e) {
         System.out.println(e.getMessage());
      }
   }
}

Output

/ by zero
raja
Published on 30-May-2019 20:31:16
Advertisements