Java list stack trace

Java — How to output stack trace (Throwable, Exception)

In Java, you can output the callstack as a Throwable object. Stack trace shows which functions have passed through to the current code position.

You can get or print Trace using the following methods of Throwable.

// Throwable.java public void printStackTrace() public void printStackTrace(PrintStream s) public StackTraceElement[] getStackTrace()

If you look at the Java code, the Exception class inherits the Throwable class. That s why Exception objects can also use Throwable s methods.

public class Exception extends Throwable  ... >

Usually, exceptions are handled using the try-catch pattern. Here, if Exception.printStackTrace() is called, a stack trace is output to the log.

try  Exception e = new Exception(); e.initCause(new IOException("No space memory")); throw e; > catch(Exception e)  e.printStackTrace(); >
java.lang.Exception at example.StackTrace$AAA.ccc(StackTrace.java:21) at example.StackTrace$AAA.bbb(StackTrace.java:14) at example.StackTrace$AAA.aaa(StackTrace.java:10) at example.StackTrace.main(StackTrace.java:47) Caused by: java.io.IOException: No space memory at example.StackTrace$AAA.ccc(StackTrace.java:22) . 3 more

Throwable also supports printStackTrace(PrintWriter s) method.

You can add a Trace to a PrintWriter by passing a PrintWriter as an argument as follows:

try  Exception e = new Exception(); e.initCause(new IOException("No space memory")); throw e; > catch(Exception e)  StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.append("+++Start printing trace:\n"); e.printStackTrace(pw); pw.append("---Finish printing trace"); System.out.println(sw.toString()); >
+++Start printing trace: java.lang.Exception at example.StackTrace$AAA.fff(StackTrace.java:50) at example.StackTrace$AAA.bbb(StackTrace.java:22) at example.StackTrace$AAA.aaa(StackTrace.java:12) at example.StackTrace.main(StackTrace.java:75) Caused by: java.io.IOException: No space memory at example.StackTrace$AAA.fff(StackTrace.java:51) . 3 more ---Finish printing trace

Output stack trace without exception

The above codes can only be used when an Exception occurs.

If you just want to print a trace for debugging purposes, create a Throwable object as shown below and call printStackTrace() . It s not a throw`, so only the log is output and the object is destroyed.

// print stack trace (new Throwable()).printStackTrace();
java.lang.Throwable at example.StackTrace$AAA.eee(StackTrace.java:39) at example.StackTrace$AAA.bbb(StackTrace.java:16) at example.StackTrace$AAA.aaa(StackTrace.java:10) at example.StackTrace.main(StackTrace.java:47)

Import as String without outputting trace

You can get the Trace as a String object without outputting it to the log.

When getStackTrace() is called as shown below, StackTraceElement array is returned. StackTraceElement object holds trace information, and the more stacks are stacked, the longer the array length. You can output the items of this object as a String.

// get stack trace and print StackTraceElement[] stacks = (new Throwable()).getStackTrace(); for (StackTraceElement element : stacks)  System.out.println(element); >
example.StackTrace$AAA.ddd(StackTrace.java:31) example.StackTrace$AAA.bbb(StackTrace.java:15) example.StackTrace$AAA.aaa(StackTrace.java:10) example.StackTrace.main(StackTrace.java:47)

The code below is the code used as an example above.

package example; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; public class StackTrace  static class AAA  void aaa()  bbb(); > void bbb()  ccc(); sleep(1000); ddd(); sleep(1000); eee(); sleep(1000); fff(); > void ccc()  try  Exception e = new Exception(); e.initCause(new IOException("No space memory")); throw e; > catch(Exception e)  e.printStackTrace(); > > void ddd()  // get stack trace and print StackTraceElement[] stacks = (new Throwable()).getStackTrace(); for (StackTraceElement element : stacks)  System.out.println(element); > > void eee()  // print stack trace (new Throwable()).printStackTrace(); > void fff()  try  Exception e = new Exception(); e.initCause(new IOException("No space memory")); throw e; > catch(Exception e)  StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.append("+++Start printing trace:\n"); e.printStackTrace(pw); pw.append("---Finish printing trace"); System.out.println(sw.toString()); > > void sleep(long ms)  try  Thread.sleep(ms); > catch (InterruptedException e)  e.printStackTrace(); > > > public static void main(String args[])  AAA a = new AAA(); a.aaa(); > >
  • Java — Remove items from List while iterating
  • Java — How to find key by value in HashMap
  • Java — Update the value of a key in HashMap
  • Java — How to put quotes in a string
  • Java — How to put a comma (,) after every 3 digits
  • BiConsumer example in Java 8
  • Java 8 — Consumer example
  • Java 8 — BinaryOperator example
  • Java 8 — BiPredicate Example
  • Java 8 — Predicate example
  • Java 8 — Convert Stream to List
  • Java 8 — BiFunction example
  • Java 8 — Function example
  • Java — Convert List to Map
  • Exception testing in JUnit
  • Hamcrest Collections Matcher
  • Hamcrest equalTo () Matcher
  • AAA pattern of unit test (Arrange/Act/Assert)
  • Hamcrest Custom Matcher
  • Hamcrest Text Matcher
  • Why Junit uses Hamcrest
  • Java — ForkJoinPool
  • Java — How to use Futures
  • Java — Simple HashTable implementation
  • Java — Create a file in a specific path
  • Java — Mockito의 @Mock, @Spy, @Captor, @InjectMocks
  • Java — How to write test code using Mockito
  • Java — Synchronized block
  • Java — How to decompile a «.class» file into a Java file (jd-cli decompiler)
  • Java — How to generate a random number
  • Java — Calculate powers, Math.pow()
  • Java — Calculate the square root, Math.sqrt()
  • Java — How to compare String (==, equals, compare)
  • Java — Calculate String Length
  • Java — case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)

Источник

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

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

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 , and ArrayIndexOutofBoundsException .

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!

Источник

Читайте также:  Csv library in python
Оцените статью