How to print message , stacktrace of Exception in java?

Many times we need the message describing the exception or the stacktrace for the exception occurred which is very useful for debugging.

1. Print message :

Java provides method getMessage() which displays the message for the exception.


try{

.....

}catch( Exception es ){
System.out.println("Message "+es.getMessage());
}


2. Printing stack trace :

To print trace of the exception Exception class provides printStackTrace method as shown below :

try{

.....

}catch( Exception es ){
es.printStackTrace();
}


3. Printing Exception Name with message :

If we use toString method then it prints exception class name along with name.


try{

.....

}catch( Exception es ){
System.out.println("Stacktrace "+es.toString());
}


Lets see it using the example :


try{
String s1 = "this is a test ";

System.out.println("Substring example "+s1.substring(0, s1.indexOf("pass")));
}catch(Exception es){
System.out.println("#############################################");
System.out.println("Exception message : "+es.getMessage() );
System.out.println("#############################################");
System.out.println("Exception message with class name : "+es.toString() );
System.out.println("#############################################");
es.printStackTrace();
}

#############################################
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
Exception message : String index out of range: -1
#############################################
Exception message with class name : java.lang.StringIndexOutOfBoundsException: String index out of range: -1
#############################################
at java.lang.String.substring(String.java:1937)
at demo.ExpDemo.main(ExpDemo.java:19)
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

1 comments:

  1. We can override toString() method of Class String and print any message which we want to display .The only thing which we should do is to create our own exception class and write a public method named toString().This class should extend the class String.When an exception of this type is thrown the complier will look for the exception class and as soon as it sees a method called toString() it immediately displays the contained message.......

    ReplyDelete