Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Java-get-example Java get Stack Trace as String

Related Tutorials


 
 

Share on Google+Share on Google+

Java get Stack Trace as String

Advertisement
In this section, you will learn how to get the stack trace of an exception as a String.

Java get Stack Trace as String

     

In this section, you will learn how to get the stack trace of an exception as a String. We are providing you an example, which is throwing an IllegalArgumentException using Throwable class.

throwable.printStackTrace(printWriter)-  This method prints the throwable exception and its stack trace to the specified print writer.

writer.toString()- This method returns the return the stack trace of an exception as a String.

Here is the code of GetStackTrace.java

import java.io.*;
public class GetStackTraceAsString{

  public static String getStackTrace(Throwable throwable) {
  Writer writer = new StringWriter();
  PrintWriter printWriter = new PrintWriter(writer);
  throwable.printStackTrace(printWriter);
  return writer.toString();
  }
  public static void main (String[]args){
  final Throwable throwable = new IllegalArgumentException("Hello");
  System.out.println( getStackTrace(throwable) );
 }

Output will be displayed as:

Download Source Code

 

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 1, 2008

Related Tutorials

Discuss: Java get Stack Trace as String  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
Leaowa Moru
May 16, 2012
get Stack Trace

I have been given the assignment about the get Stack Trace and I have to find the real meaning not program so that I understand it correctly
DMCA.com