tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > IO > Get Exception Trace

Get Exception Trace 

The following example shows how to get the exception stack trace as a string.

File Name  :  
com/bethecoder/tutorials/io/ExceptionTrace.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.io;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

public class ExceptionTrace {

  /**
   @param args
   */
  public static void main(String[] args) {

    try {
      throwException();
    catch (Exception e) {
      //The exception stack message can be written to
      //console or a log file or even we can
      //send a mail with the trace.
      
      String stackTrace = getStackTrace(e);
      
      System.out.println("****** ERROR ********");
      System.out.println(stackTrace);
      System.out.println("****** ERROR ********");
    }
  }
  
  private static void throwException() {
    if (true) {
      throw new RuntimeException("Some user exception");
    }
  }
  
  public static String getStackTrace(Throwable throwable) {
    Writer result = new StringWriter();
    PrintWriter printWriter = new PrintWriter(result);
    throwable.printStackTrace(printWriter);
    return result.toString();
  }
}
   

It gives the following output,
****** ERROR ********
java.lang.RuntimeException: Some user exception
	at com.bethecoder.tutorials.io.ExceptionTrace.throwException(ExceptionTrace.java:31)
	at com.bethecoder.tutorials.io.ExceptionTrace.main(ExceptionTrace.java:15)

****** ERROR ********



 
  


  
bl  br