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



Home Java Java-get-example Java get Stack Trace

Related Tutorials


 
 

Share on Google+Share on Google+

Java get Stack Trace

Advertisement
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 GetStackTrace.java

import java.io.*; 

class GetStackTrace { 
 public static void main (String[] args) {  
  DataInputStream dis = null
  String data = null
  int count = 0
  try 
 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 ) { 
 count++; 
  System.out.println(count + ": " + data); 
 
 catch (Exception e) { 
  e.printStackTrace(); 
 
  

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  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com