Java.lang.Throwable.printStackTrace() Method

Advertisements


Description

The java.lang.Throwable.printStackTrace() method prints this throwable and its backtrace to the standard error stream. It prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err.

Declaration

Following is the declaration for java.lang.Throwable.printStackTrace() method

public void printStackTrace()

Parameters

  • NA

Return Value

This method does not return any value.

Exception

  • NA

Example

The following example shows the usage of java.lang.Throwable.printStackTrace() method.

package com.tutorialspoint;

import java.lang.*;

public class ThrowableDemo {

   public static void main(String[] args) {

      try {
         ExceptionFunc();
      }
      catch(Throwable e) {
         // prints stacktace for this Throwable Object
         e.printStackTrace();
      }
   }
  
   public static void ExceptionFunc() throws Throwable {

      Throwable t = new Throwable("This is new Exception...");
      StackTraceElement[] trace = new StackTraceElement[] {
         new StackTraceElement("ClassName","methodName","fileName",5)
      };

      // sets the stack trace elements
      t.setStackTrace(trace);
      throw t;
   }
} 

Let us compile and run the above program, this will produce the following result:

java.lang.Throwable: This is new Exception...
at ClassName.methodName(fileName:5)



Advertisements
Advertisements