Various Methods for Printing Exception Message
There are three ways to print an Exception message to the console.
1-Using java.lang.Exception Object
"An Exception class object prints the message and type of exception."
Demo Program
package com.navneet.javatutorial;public class ExceptionMessageDemo{
public static void main(String[] args) {
try{
System.out.println(10/0);
}
catch(ArithmeticException e){
System.out.println(e);
}finally{
System.out.println("Finally Block statement");
}}
}
O/P:
java.lang.ArithmeticException: / by zero
Finally Block statement
2-Using getMessage method of (java.lang.Throwable Class)
This method only display the exception message.
Demo Example:
package com.navneet.javatutorial;
public class ExceptionMessageDemo {
public static void main(String[] args) {
try{
System.out.println(10/0);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}finally{
System.out.println("Finally Block statement");
}}
}
O/P:
/ by zero
Finally Block statement
3-Using printStackTrace() method of (java.lang.Throwable Class)
This method print the name of the exception and type of the exception message and line number where exception has raised.
Demo Program
package com.navneet.javatutorial;public class ExceptionMessageDemo1 {
public static void main(String[] args) {
try{
System.out.println(10/0);
}
catch(ArithmeticException e){
e.printStackTrace();
}finally{
System.out.println("Finally Block statement");
}}
}
O/P :
java.lang.ArithmeticException: / by zero
at com.navneet.javatutorial.ExceptionMessageDemo1.main(ExceptionMessageDemo1.java:9)
Finally Block statement