Java Exception stack trace

What is an exception stack trace?

Exception stack trace is a combination of exception name, description and call stack. The stack trace contains all method calls from the start of a thread to till the point where exception raised. The stack trace is produced automatically by the Java Virtual Machine.

A stack trace is a very helpful debugging tool, Because it doesn’t only shows what the error occurred and where the error occurred, but also shows the stack of methods that were called up to the point where exception occurred.

StackTraceExample : Here we are printing stack trace with public void printStackTrace() method of an Exception class.

Output :

java.lang.IllegalArgumentException: some error
at com.vidvaan.corejava.exception03.stackTrace.ExceptionStackTraceExample.method4(
at com.vidvaan.corejava.exception03.stackTrace.ExceptionStackTraceExample.method3(
at com.vidvaan.corejava.exception03.stackTrace.ExceptionStackTraceExample.method2(
at com.vidvaan.corejava.exception03.stackTrace.ExceptionStackTraceExample.method1(
at com.vidvaan.corejava.exception03.stackTrace.ExceptionStackTraceExample.main(

The stack trace is encapsulated into an array of java.lang.StackTraceElement. This array returned by Throwable.getStackTrace() method. Each element represents a single stack frame in the call stack. StackTraceElement encapsulates following information.

How to Convert exception stack trace into string

Some times we may required to convert the stack trace to java.lang.String format. Below is an example to convert stack trace into String.

How to Log exceptions in Projects ?

In Project we never ever use public void printStackTrace() to print stack trace. Because this will print the stack trace into console which is not permanent for future references. In project we always print the stack traces into log files.

The good news is that most loggers, including Log4j and Logback, will write exceptions with stack traces into log files if you call them with the right arguments.

If you use SLF4J or Log4j or Logback, Logging error code looks like as follows:

Scroll to Top