logo

Método Java Throwable printStackTrace()

O método printStackTrace() da classe Java Throwble é usado para imprimir o Throwable junto com outros detalhes como nome da classe e número da linha onde ocorreu a exceção.

Sintaxe

 public void printStackTrace() 

Retornar

Exemplo 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()); } } } 
Teste agora

Saída:

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

Exemplo 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!'); } } 
Teste agora

Saída:

aprendizado de máquina supervisionado
 Inside exceptionTest() method java.lang.Exception: Throwing localized message! at ThrowablePrintStackTraceExample2.exceptionTest(ThrowablePrintStackTraceExample2.java:11) at ThrowablePrintStackTraceExample2.main(ThrowablePrintStackTraceExample2.java:4)