Trace java exception has occurred

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)

Источник

Understanding Exception Stack Trace in Java with Code Examples

This Java exception tutorial helps you understand the concept of exception stack trace in Java and how to analyze an exception stack trace to detect bugs.

In this tutorial, we use the example in the article Understanding Java Exception Chaining with Code Examples. So kindly refer to that article while reading this one.

1. Analyzing an Exception Stack Trace

StudentException: Error finding students at StudentManager.findStudents(StudentManager.java:13) at StudentProgram.main(StudentProgram.java:9) Caused by: DAOException: Error querying students from database at StudentDAO.list(StudentDAO.java:11) at StudentManager.findStudents(StudentManager.java:11) . 1 more Caused by: java.sql.SQLException: Syntax Error at DatabaseUtils.executeQuery(DatabaseUtils.java:5) at StudentDAO.list(StudentDAO.java:8) . 2 more

By examining this information we can find the root cause of the problem in order to fix bugs. In this exception stack trace, you see a list of chained exceptions which is sorted by the exception at the highest level to the one at the lowest level. This forms a stack like a stack of cards.

In each trace, we see the exception type (exception class name) along with the message:

StudentException: Error finding students
at StudentManager.findStudents(StudentManager.java:13)

This line tells us that the StudentException was thrown at line 13 in the method findStudents() of the class StudentManager.

And what causes the StudentException ? Look at the next trace, we see:

Caused by: DAOException: Error querying students from database

That means the StudentException is caused by the DAOException which is thrown at line 11 in the method list() of the StudentDAO class.

Continue investigating further until the last exception in the trace, we see that the SQLException is actually the root cause and the actual place that sparks the exception is at line 5 in the method executeQuery() of the DatabaseUtils class:

Caused by: java.sql.SQLException: Syntax Error at DatabaseUtils.executeQuery(DatabaseUtils.java:5)
import java.sql.*; public class DatabaseUtils < public static void executeQuery(String sql) throws SQLException < throw new SQLException("Syntax Error"); >>

So basically that’s how we analyze the exception stack trace to find the root cause of the bug. The root cause is always at the bottom of the stack.

2. Preventing Exceptions Lost

Chaining exceptions together is a good practice, as it prevents exceptions from losing in the stack trace. Let’s modify the StudentDAO class like this:

import java.sql.*; public class StudentDAO < public void list() throws DAOException < try < DatabaseUtils.executeQuery("SELECT"); >catch (SQLException ex) < throw new DAOException("Error querying students from database"); >> >

Here we remove the SQLException instance ( ex ) from the DAOException ’s constructor. Let’s compile and run the StudentProgram again, we would get the following output:

StudentException: Error finding students at StudentManager.findStudents(StudentManager.java:13) at StudentProgram.main(StudentProgram.java:11) Caused by: DAOException: Error querying students from database at StudentDAO.list(StudentDAO.java:11) at StudentManager.findStudents(StudentManager.java:11) . 1 more

By comparing this exception stack trace with the previous one, we see that the SQLException disappears, right? That means the SQLException is lost in the stack trace though it is actually the root cause. When this happens, it’s hard to detect bugs exactly as the truth is hidden.

So you understand the importance of chaining exceptions together, don’t you?

3. Working with Exception Stack Trace

Besides the printStackTrace() method which prints out the detail exception stack trace, the Throwable class also provides several methods for working with the stack trace. Here I name a few.

    The printStackTrace(PrintStream) method writes the stack trace to a file stream. For example:

> catch (StudentException ex) < try < PrintStream stream = new PrintStream(new File("exceptions1.txt")); ex.printStackTrace(stream); stream.close(); >catch (FileNotFoundException fne) < fne.printStackTrace(); >>
> catch (StudentException ex) < // print stack trace to a PrintWriter try < PrintWriter writer = new PrintWriter(new File("exceptions2.txt")); ex.printStackTrace(writer); writer.close(); >catch (FileNotFoundException fne) < fne.printStackTrace(); >>
> catch (StudentException ex) < StackTraceElement[] stackTrace = ex.getStackTrace(); for (StackTraceElement trace : stackTrace) < String traceInfo = trace.getClassName() + "." + trace.getMethodName() + ":" + trace.getLineNumber() + "(" + trace.getFileName() + ")"; System.out.println(traceInfo); >>

Consult the Javadoc of the Throwable class to see more methods like fillInStackTrace() , setStackTrace() , etc.

4. A good practice about exception handling

Don’t handle exceptions in the intermediate layers, because code in the middle layers is often used by code in the higher layers. It’s responsibility of the code in the top-most layer to handle the exceptions. The top-most layer is typically the user interface such as command-line console, window or webpage. And typically we handle exceptions by showing a warning/error message to the user.

This good practice is illustrated by the following picture:

exception chaining rule

So remember this rule when designing and coding your program.

References:

Other Java Exception Handling Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Читайте также:  Unable to install java optifine
Оцените статью