Different Ways to Print Exception Messages in Java
Last Updated :
06 Dec, 2021
In Java, there are three methods to print exception information. All of them are present in the Throwable class. Since Throwable is the base class for all exceptions and errors, we can use these three methods on any exception object.
Methods to Print Exceptions in Java
There are three methods to print exception messages in Java. These are:
1. java.lang.Throwable.printStackTrace() method:
By using this method, we will get the name(e.g., java.lang.ArithmeticException) and description(e.g., / by zero) of an exception separated by a colon, and the stack trace (wherein the code, that exception has occurred) in the next line.
Syntax:
public void printStackTrace()
Java
public class Test {
public static void main(String[] args)
{
try {
int a = 20 / 0 ;
}
catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
}
|
Runtime Exception:
java.lang.ArithmeticException: / by zero
at Test.main(Test.java:9)
Output:
java.lang.ArithmeticException: / by zero
2. toString() method:
Using this method will only get the name and description of an exception. Note that this method is overridden in the Throwable class.
Java
public class Test {
public static void main(String[] args)
{
try {
int a = 20 / 0 ;
}
catch (Exception e) {
System.out.println(e.toString());
}
}
}
|
Output
java.lang.ArithmeticException: / by zero
3. java.lang.Throwable.getMessage() method:
Using this method, we will only get a description of an exception.
Syntax:
public String getMessage()
Java
public class Test {
public static void main(String[] args)
{
try {
int a = 20 / 0 ;
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...