Share on Google+Share on Google+

Java get Stack Trace

In this section, you will learn how to obtain the stack trace.

Java get Stack Trace


In this section, you will learn how to obtain the stack trace.

When you want to generate an exception in a program, it will be better to print out the exception stack trace to catch the error instead of using e.getMessage() method. By  the stack trace, you will know which method threw an exception and how that method is called. The method printStackTrace() method prints a stack trace from the exception and provides more information about the error process.

In the given example, we are trying to read the non-existent file 'data.txt' file by using the method dis.readLine(). Therefore, FileNotFoundException occurs.

Here is the code of


class GetStackTrace { 
 public static void main (String[] args) {  
  DataInputStream dis = null
  String data = null
  int count = 0
 File f = new File("data.txt");  
 FileInputStream fis = new FileInputStream(f);  
 BufferedInputStream bis = new BufferedInputStream(fis);  
 dis = new DataInputStream(bis);  

 while ( (data=dis.readLine()) != null ) { 
  System.out.println(count + ": " + data); 
 catch (Exception e) { 

Output will be displayed as

Download Source Code


Posted on: November 1, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles

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.

Discuss: Java get Stack Trace  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image