Java Throwable - printStackTrace() Method
The java.lang.Throwable.printStackTrace() method is used to print this throwable and its backtrace to the standard error stream. This method prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err.
Syntax
public void printStackTrace()
Parameters
No parameter is required.
Return Value
void type.
Exception
NA.
Example:
The example below shows how to use the java.lang.Throwable.printStackTrace() method.
import java.lang.*; public class MyClass { public static void main(String[] args) throws Throwable { try{ int x = 10, y = 0, z; z = x/y; System.out.println(z); } catch (Exception e){ e.printStackTrace(); } } }
The output of the above code will be:
java.lang.ArithmeticException: / by zero at MyClass.main(MyClass.java:7)
Example:
Consider one more example to understand the concept better.
import java.lang.*; public class MyClass { public static void main(String[] args){ try{ testException(); } catch (Exception e){ e.printStackTrace(); } } //method to throw Exception public static void testException() throws Exception { throw new Exception("New Exception Thrown"); } }
The output of the above code will be:
java.lang.Exception: New Exception Thrown at MyClass.testException(MyClass.java:15) at MyClass.main(MyClass.java:6)
❮ Java.lang - Throwable