Q:

Java program to print the stack trace of an exception

belongs to collection: Java Exception Handling Programs

0

Java program to print the stack trace of an exception

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will print a stack trace of generated exceptions using the printStackTrace() method.

Program/Source Code:

The source code to print the stack trace of an Exception is given below. The given program is compiled and executed successfully.

// Java program to print the stack trace 
// of an Exception.

public class Main {
  public static void main(String[] args) {
    try {
      String str = null;

      int len = str.length();

      System.out.println("Length of string: " + len);
    } catch (Exception e) {
      e.printStackTrace();
    }

    System.out.println("Program Finished");
  }
}

Output:

java.lang.NullPointerException
        at Main.main(Main.java:9)
Program Finished

Explanation:

In the above program, we created a class Main. The Main class contains a main() method. The main() method is the entry point for the program.

Here, we created try and catch blocks. In the try block, an exception gets generated, and then the exception is caught in the catch block and we printed the stack trace of generated exception.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to implement the try block with multi... >>
<< Java program to handle StringIndexOutOfBoundsExcep...