×

Different Ways to Print Exception Message in Java

In this section, we will learn how to use various Java Throwable class methods to print exception messages. The Throwable class has the three methods listed below for printing the exception message:

  • Using the printStackTrace Method
  • Employing the getMessage() Method
  • utilizing the method toString()

Various Java Methods for Printing Exceptional Messages Let's go over each in more depth one by one.

Using the printStackTrace() method

The Throwable class, which is a part of the java.lang package, contains the definition of the printStackTrace() method. The method outputs an exception's title, description (such as "/ by zero," line number, and class name), and stack trace. The subsequent exception's location is shown on the stack trace. The exception message can be printed with great frequency.

The printStackTrace() method comes in three different iterations:

SyntaxDescription
printStackTrace()That throwable as well as its backtrace are printed by the method toward the standard deviation stream.
public void printStackTrace(PrintStream h)The throwable as well as its backtrace are printed by the method to the designated print stream.
public void printStackTrace(PrintWriter h)    The throwable as well as its backtrace are printed by the procedure to the designated print writer.

We will first develop a Java program that produced a divide by zero exception in order to better grasp the notion behind the printStackTrace() method. The printStackTrace() method will not be used in this program to print the exception.

PrintExceptionMessageDemo1.java

public class PrintExceptionMessageDemo1  
{  
//the user defined method  
public static void divide()   
{  
try   
{  
// raised exception for division by zero
int b = 100/0;  
}  
catch (Exception e)   
{  
//exception message is printed
System.out.println(e);  
}  
}  
//it is the main() method  
public static void main(String args[])   
{  
// the use of a user-defined method
divide();  
}  
} 

The following message appears on the console when the aforementioned application is run, and we encounter an arithmetic exception:

Output:

java.lang.ArithmeticException: / by zero

We are unable to identify the line in the message that throws the exception. Thus, it is challenging to identify instances of exceptions. We utilise the printStackTrace() method to solve this issue. Let's use a Java programme to use the printStackTrace() method.

PrintExceptionMessageDemo2.java

public class PrintExceptionMessageDemo2.java
{  
//It is the user defined method  
public static void divide()   
{  
try   
{  
//it is raised divide by the zero exception  
int b = 100/0;  
}  
catch (Exception e)   
{  
//displays the exception's message and specifics  
e.printStackTrace();  
}  
}  
//it is the main() method  
public static void main(String args[])   
{  
// user defined method is called
divide();  
}  
}

Output:

Java.lang.ArithmeticException: / by zero
              at PrintExceptionMessageDemo2.divide(PrintExceptionMessageDemo2.java:9)
              at PrintExceptionMessageDemo2.main(PrintExceptionMessageDemo2.java:21)

The exception message mentioned above makes it apparent which procedure raised the error, what kind of error it was, and which line actually threw the error.

The application throws a java.lang, as can be seen in the message's first line.

ArithmeticException (division by zero) (divide by zero). The second line demonstrates that the procedure division() throws an exception and that exceptions start to occur at line 9. That exception is shown at line 21 of the third line. Because the split() method is invoked inside the main() method, the main() method similarly throws an exception. In light of this, we can quickly identify the precise location of the exception by using the printStackTrace() method.

Employing the getMessage() Method

The Throwable class, which is a part of the java.lang package, also contains the definition of the getMessage() method. Just the information of an exception is printed by the technique. Neither the exception's name nor its description is printed. The exception message can be printed with great frequency.

Syntax:

public String getMessage();

The throwable instance's detailed message string is returned via the function. It might be empty.

Let's use the Java program's getMessage() method.

public class PrintExceptionMesssageDemo3.java  
{   
public static void main(String args[])   
{   
try  
{   
int b = 100/0;   
}   
catch (Exception e)   
{   
//message of the exception is only printed  
System.out.println(e.getMessage());       
// Using the following statement will print the title of the exception and the exception that was thrown.
//System.out.println(e);   
}   
}   
}

Output:

/ by zero

It merely prints the exception, as we can see. Due to the lack of a thorough description of an exception, it is not generally utilised.

Utilizing the method toString()

The throwable class's toString() method takes precedence over the Object class's toString() method. It outputs an exception's succinct description. The other details aren't displayed (like exception name and stack trace). The printing of exception messages is not very common.

Consider implementing the toString()method in a Java program.

public class PrintExceptionMessageDemo4  
{   
public static void main(String args[])   
{   
try  
{   
int b = 100/0;   
}   
catch (Exception e)   
{   
// The exception message can be printed using 
// either of the statements; both print the same message.
System.out.println(e.toString()); //System.out.println(e);  
}   
}   
}  

Output:

Java.lang.ArithmeticException: / by zero

We can see from the message above that it just prints the exception's name and kind. It does not specify the line number where the exception occurred.

We have examined the various Java exception message printing methods. Because it identifies the place an error occurs, we advise using the printStackTrace() method.


Related Topics

Java.lang.Exception.NoRunnableMethods

In Programming language, the java lang unexpected no precompiled methods error generally refers to a Junit exception that happens whenever Junit is incapable of locate the precompiled test methods. When...

4 minutes read.

CopyOnWriteArrayList in Java

The CopyOnWriteArrayList is used to implement the List Interface. It is the improved version of ArrayList. The operations like add, remove, set, update etc, these operations are done by creating...

5 minutes read.

How to Return Value from Lambda Expression Java?

What is Lambda Expression in Java? In Java 8, Lambda Expressions were introduced.A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods,...

4 minutes read.

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Even Odd Program in Java

Even Odd Program in Java The number that are completely divisible by 2 are even and the number that leaves remainder are odd numbers. For example, the numbers 2, 0, 4,...

5 minutes read.

How to check valid date in Java?

Every time we get data for any application, we must first ensure that it is accurate before continuing with any further processing. We might have to confirm the following while dealing...

4 minutes read.

String vs StringBuilder

String vs StringBuilder In this section, we will discuss the comparison between Java String and StringBuilder class. String In Java, a string is treated as an object that represents a sequence of characters....

4 minutes read.

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.

Compile-time Error in Java

In java, the execution of a program is stopped due to the occurrence of some problem known as an error. Errors are illegal operations that are carried out by the...

4 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

How to set timer in Java

In this article, you will be very well equipped with the knowledge to set timer in java. The timer in java can be set by using timer class provided by...

3 minutes read.

Object class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM mostly generally...

6 minutes read.

Java Math getExponent() Method

The getExponent() method of Math class returns the unbiased exponent of the argument. Syntax: public static int getExponent (double d) Parameters: The parameter ‘d’ represents the double value. Return Value: The getExponent () method returns the...

1 minute read.

Difference between final, finally, and finalize()

Difference between final, finally, and finalize() In Java, final, finally and finalize sound similar they are totally different in functionality. Final and finally are the two keywords but the finalize is...

4 minutes read.

MOOD Factors to Assess a Java Program

In this tutorial, we will comprehendthe meaning of mood factors in Java. For the development of any software system,the quality of anapplication is important. It is more important to maintain large-scale...

4 minutes read.

How annotations work in Java

Annotations were introduced by sun microsystem and are available from the java 1.5 version. In general, configurations can be done either by XML or by annotations. Hibernate and spring framework users prefer...

4 minutes read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

3 minutes read.