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)

Updated on: 14-Sep-2023

28K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements