×

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

How to Reverse a String in Java

How to Reverse a String in Java There are a lot of ways to reverse a string in Java. One can use iteration, StringBuilder, StringBuffer to do the reverse of a...

6 minutes read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Java Enumeration

In a computer language, enumerations express a set of named constants. For instance, the four suits in a deck of playing cards could be represented by the enumerators Club, Diamond,...

4 minutes read.

Java Architecture

Java architecture is a combination of three parts they are JVM, JRE and JDK. These components will help in the functioning of the java programs. The process of code interpretation...

6 minutes read.

Java Generate UUID

What java Generate UUID? A 128-bit long value that is universally unique serves as the basis for the terms UUID (Universally Unique Identifier) and GUID (Globally Unique Identifier). Hexadecimal (octet) digits...

5 minutes read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

The Diamond Operator in Java 7

The Diamond operator is a comparatively recent Java operator originally developed in JDK 7 to enhance type identification and eliminate boilerplate Java code. The Diamond operator is characterized by a...

2 minutes read.

Trimorphic numbers in Java

Wondered what the Trimorphic number is!! In this article, you can learn about what a Trimorphic number is referred to as and how to find whether a number is trimorphic...

3 minutes read.

Short Circuit Logical Operators in Java

When there are two or more relational expressions in a decision-making statement, logical operators are utilized to combine them. The logical operators short circuit and not-short circuit fall into two...

5 minutes read.

How to Read CSV Files in Java?

Comma-Separated Values is the acronym for this format. It is a straightforward file format storing textual tabular data in a database or spreadsheet. The CSV files can be imported into...

3 minutes read.

How to resolve Illegal state exceptions in Java

What is IllegalStateException? When a method is called at the incorrect time, a runtime exception called an IllegalStateException is raised in Java. This exception is utilized to show that a method...

3 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

Undo and Redo Operations in Java

Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java. Undo Redo...

2 minutes read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.

Java Package Keyword

A collection of classes, interfaces, and subpackages in a Java program are referred to as a package. Here, we'll learn in-depth how to make and use user-defined packages. package is a...

6 minutes read.

How to convert String to String array in Java

A String in Java is a thing that indicates a collection of letters. We must include the String class from java.lang package if we want to be using strings. An...

5 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.