Tuesday, 9 January 2018

Different ways to Print Exception Messages | Java

Tags

There are three methods available in Java to print the exception messages. Those three methods are the member of Throwable class. These three methods can be used to print the exception message for any exception object because Throwable class is the base class for all exceptions.


Method 1:


java.lang.Throwable.printStackTrace(): This method is used to get the exception name (e.g. java.lang.Arithmetic Exception), description(e.g  / by zero) separated by colon as well as stack trace (where in the code exception has occurred) on new line.

Example:

import java.lang.*;
import java.util.*;

class exception_message{
 

    public static void main(String args[]){

             Scanner in=new Scanner(System.in);
             int a,b;

             System.out.println("\nEnter the value of a: \n");
             a=in.nextInt();

             System.out.println("\nEnter the value of b:\n");
             b=in.nextInt();

             try{
                    int c=a/b;
             }
             catch(Exception e){

                       System.out.print("\n");
                       //It will print the line number and call stack
                    e.printStackTrace();

                       //This function will print the thrown exception
                    System.out.print("\n"+e);
             }



    }
}

Output:



Method 2:

java.lang.Throwable.toString(): This method returns the "exception name + description"  as a string separated by colon. Unlike printStackTrace() this method to not return the stack trace of the exception occurred in the code.

Example:

import java.lang.*;
import java.util.*;

class exception_message{
 

    public static void main(String args[]){

             Scanner in=new Scanner(System.in);
             int a,b;

             System.out.println("\nEnter the value of a: \n");
             a=in.nextInt();

             System.out.println("\nEnter the value of b:\n");
             b=in.nextInt();

             try{
                    int c=a/b;
             }
             catch(Exception e){
                       
                        System.out.print("\n"+e.toString());
             }



    }
}


Output:



Method 3:

java.lang.Throwable.getMessage(): This method is used to get only description of the exception.

Example:

import java.lang.*;
import java.util.*;

class exception_message{
 

    public static void main(String args[]){

             Scanner in=new Scanner(System.in);
             int a,b;

             System.out.println("\nEnter the value of a: \n");
             a=in.nextInt();

             System.out.println("\nEnter the value of b:\n");
             b=in.nextInt();

             try{
                    int c=a/b;
             }
             catch(Exception e){
                       
                        System.out.print("\n"+e.getMessage());
             }



    }
}

Output:




EmoticonEmoticon