Friday, 2 September 2016

Different Ways to Print Exception Message in Java.

There are 3 Ways to print Exception Message :-
1 > Using Object of java.lang.Exception. This Only Prints the Exception Name.

2 > Using printStackTrace() Method. This is the method which is defined in java.lang.Throwable class and it is inherited from java.lang.Error class and java.lang.Exception class.This method display the name of the Exception and Line where the Exception has Occurred in the Program.

3 > Using getMessage() Method. This method only display the Exception Message.

public class WaysToPrintExceptionMsg {

public static void method_1(){
String s1=null;
try {
s1.length();
} catch (Exception e) {
System.out.println(e);

}
}
public static void method_2(){
String s1=null;
try {
s1.length();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void method_3(){
try {
int x=1/0;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
System.out.println("METHOD 1 OUTPUT :- ");
WaysToPrintExceptionMsg.method_1();
System.out.println("\n\nMETHOD 2 OUTPUT :- ");
WaysToPrintExceptionMsg.method_2();
System.out.println("\n\nMETHOD 3 OUTPUT :- ");
WaysToPrintExceptionMsg.method_3();
}

}
Program Output :-
METHOD 1 OUTPUT :- 
java.lang.NullPointerException


METHOD 2 OUTPUT :- 
java.lang.NullPointerException
at exceptions.programs.WaysToPrintExceptionMsg.method_2(WaysToPrintExceptionMsg.java:23)
at exceptions.programs.WaysToPrintExceptionMsg.main(WaysToPrintExceptionMsg.java:39)


METHOD 3 OUTPUT :- 
/ by zero




No comments:

Post a Comment