Blog |

What is a Java Stack Trace? How to Read & Analyze Traces

What is a Java Stack Trace? How to Read & Analyze Traces
Table of Contents

A Java stack trace is displayed when an error or exception occurs. The stack trace, also called a backtrace, consists of a collection of stack records, which store an application's movement during its execution.

The stack trace includes information about program subroutines and can be used to debug or troubleshoot and is often used to create log files. These exceptions could be custom (defined by the user) or built-in. Examples include RuntimeException,NullPointerException, andArrayIndexOutofBoundsException.

Now that you know what a stack trace is, let’s take a look at some examples, how to analyze stack traces, and how you can avoid a stack trace altogether with error handling.

 

Examples of Java Stack Traces

Example 1 - Temperature Conversion from Celsius to Fahrenheit

Let's look at an example of converting temperatures from Celsius to Fahrenheit. Only an integer or float input is valid here. But if we try to provide another data type, such as a string, the compiler will throw an exception and print the stack trace.


import java.util.Scanner;

public class hello{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter value in Celsius to convert in fahrenheit:");

        double Celsius = scanner.nextFloat();
        double fahrenheit = (Celsius * 1.8)+32;

        System.out.printf("%.1f degrees Celsuis is %.1f degrees in Fahrenheit ",Celsius,fahrenheit);
    }
}

When we run the above code and enter some invalid value, let’s say the string "hero," we get the following output:

Enter value in Celsius to convert in fahrenheit: hero
Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextFloat(Scanner.java:2496)
    at com.example.myJavaProject.hello.main(hello.java:12)

 

Example 2 - Function Chaining

This is an example of function chaining, in which one function calls another in a chain-like fashion. Unlike in Example 1, no exception is thrown here, but the stack trace is explicitly printed using the dumpstack() method (a useful method when creating log files). This is good practice because we can use this code later for maintenance or to check the overall health or condition of the application.

public class Example {
   public static void main(String args[]) {
       f1();
   }

   static void f1() {
       f2();
   }

   static void f2() {
       f3();
   }

   static void f3() {
       f4();
   }

   static void f4() {
       Thread.dumpStack();
   }

}

When the above code is executed, we get the following output:

java.lang.Exception: Stack trace
    at java.base/java.lang.Thread.dumpStack(Thread.java:1380)
    at com.example.myJavaProject.Example.f4(Example.java:25)
    at com.example.myJavaProject.Example.f3(Example.java:20)
    at com.example.myJavaProject.Example.f2(Example.java:15)
    at com.example.myJavaProject.Example.f1(Example.java:10)
    at com.example.myJavaProject.Example.main(Example.java:6)

 

How to Read and Analyze Example 1’s Stack Trace

Let’s consider Example 1 for this analysis. Below is the breakdown of the output from its execution:

The first line in the stack trace:

First line in stack trace

The bottom line in the stack trace:

Bottom line in stack trace

Now, let’s look at the entire stack trace and try to analyze it:

Enter value in Celsius to convert in fahrenheit: hero
Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextFloat(Scanner.java:2496)
    at com.example.myJavaProject.hello.main(hello.java:12)

The main() method is at the bottom of the stack because that is where the program began. By reading from bottom to top, we can now identify where and what exception is being raised. Tracing the source of this error back to the main() method reveals that an exception occurs when the user's input is taken.

The second line from the top shows that the float input was taken using the function nextFloat(), which in turn calls the next() function, which in turn calls the throwFor() function. As a result, it throws an InputMismatchException.

 

How to Fix Example 1’s Code Using Error Handling and Stack Traces

Stack traces and exceptions are clearly related, as evidenced by the preceding examples. Stack traces can be avoided; in short, some common error handling techniques can be used to handle and resolve any exceptions thrown by the code during execution. The technique listed below can help avoid a stack trace.

Examine, Investigate, and Handle Java Errors

It's common for amateur programmers to overlook exceptions in their code. Being able to examine, investigate, and handle mistakes can be very helpful prior to moving to the next step. Let’s handle the exception in Example 1 by using try and catch statements.

import java.util.Scanner;

public class hello {
   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);

       System.out.print("Enter value in Celsius to convert in fahrenheit:");

       try {

           double Celsius = scanner.nextFloat();
           double fahrenheit = (Celsius * 1.8) + 32;

           System.out.printf("%.1f degrees Celsuis is %.1f degrees in Fahrenheit ", Celsius, fahrenheit);
       } catch (InputMismatchException e) {
           System.out.println("Wrong input type entered...exiting the program");
       }

   }
}

In the above code, we have used a try-catch block to catch the exception and then print a custom message to notify the user to enter a valid input.

When the code above is executed, we get the following output:

Enter value in Celsius to convert in fahrenheit: hero
Wrong input type entered...exiting the program

Process finished with exit code 0

With the help of the try and catch blocks, the code to be tested is placed in the try block and any exception thrown by the code is handled in the catch block.

This is the most commonly used method to handle exceptions in Java and thus avoid stack traces.

 

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyse, and manage errors in real-time can help you proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape