logo

Metoda Java Throwable printStackTrace().

Metoda printStackTrace() klasy Java Throwble służy do wypisywania wartości Throwable wraz z innymi szczegółami, takimi jak nazwa klasy i numer wiersza, w którym wystąpił wyjątek.

Składnia

 public void printStackTrace() 

Powrót

Przykład 1

 import java.lang.Throwable; public class ThrowablePrintStackTraceExample1 { public static void main(String[] args) throws Throwable { try{ int i=4/0; }catch(Throwable e){ e.printStackTrace(); System.err.println('Cause : '+e.getCause()); } } } 
Przetestuj teraz

Wyjście:

 java.lang.ArithmeticException: / by zero at ThrowablePrintStackTrace.main(ThrowablePrintStackTrace.java:5) Cause : null 

Przykład 2

 public class ThrowablePrintStackTraceExample2 { public static void main(String[] args)throws Throwable { try{ exceptionTest(); }catch(Throwable t){ t.printStackTrace(); } } public static void exceptionTest() throws Exception{ System.out.println('Inside exceptionTest() method'); throw new Exception('Throwing localized message!'); } } 
Przetestuj teraz

Wyjście:

Linux, które polecenie
 Inside exceptionTest() method java.lang.Exception: Throwing localized message! at ThrowablePrintStackTraceExample2.exceptionTest(ThrowablePrintStackTraceExample2.java:11) at ThrowablePrintStackTraceExample2.main(ThrowablePrintStackTraceExample2.java:4)