Java get Stack Trace

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

Java get 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