English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

¿Cómo imprimir un mensaje personalizado en lugar de ErrorStackTrace en Java?

Las excepciones son problemas que ocurren durante la ejecución del programa (errores de tiempo de ejecución). Cuando ocurre una excepción, el programa se detiene repentinamente y el código que sigue a la línea de excepción nunca se ejecutará.

Imprimir mensaje de excepción

Puede usar uno de los siguientes métodos heredados de la clase Throwable para imprimir mensajes de excepción en Java.

  • printStackTrace() -Este método imprime el rastreo de llamadas en el flujo de error estándar.

  • getMessage() -Este método devuelve una cadena de mensaje detallada del objeto que se puede lanzar.

  • toString() -Este mensaje muestra una descripción breve del objeto que se puede lanzar.

Ejemplo

import java.util.Scanner;
public class PrintingExceptionMessage {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter first number:");
      int a = sc.nextInt();
      System.out.println("Enter second number:");
      int b = sc.nextInt();
      try {
         int c = a/b;
         c);+catch(ArithmeticException e) {
      }
         System.out.println("Salida de printStackTrace() método: ");
         e.printStackTrace();
         System.out.println(" ");
         System.out.println("Salida del método getMessage(): ");
         System.out.println(e.getMessage());
         System.out.println(" ");
         System.out.println("Salida del método toString(): ");
         System.out.println(e.toString());
      }
   }
}

Resultado de salida

Enter first number:
10
Enter second number:
0
Salida del método printStackTrace():
java.lang.ArithmeticException: / por zero
Salida del método getMessage():
/ por zero
Salida del método toString():
java.lang.ArithmeticException: / por zero
at PrintingExceptionMessage.main(PrintingExceptionMessage.java:11)

Imprimir mensaje de excepción personalizada

Rethrow excepción-Puede rethrow una excepción capturada en un bloque catch utilizando la palabra clave new, al hacerlo, debe pasar el objeto de excepción capturado y el String que representa el mensaje juntos, luego mostrar el mensaje original transmitido.

Ejemplo

import java.util.Scanner;
public class PrintingExceptionMessage {
   public static void main(String args[]) throws Exception {}}
      String msg = "Este es mi mensaje personalizado";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter first number:");
      int a = sc.nextInt();
      System.out.println("Enter second number:");
      int b = sc.nextInt();
      try {
         int c = a/b;
         c);+catch(ArithmeticException e) {
      }
         throw new Exception("CoustomMessage: " );+msg, e);
      }
   }
}

Resultado de salida

Enter first number:
25
Enter second number:
0
Excepción en el hilo "main" java.lang.Exception: CoustomMessage: Este es mi mensaje personalizado
at july_set3.PrintingExceptionMessage.main(PrintingExceptionMessage.java:)16)
Causado por: java.lang.ArithmeticException: / por zero
at july_set3.PrintingExceptionMessage.main(PrintingExceptionMessage.java:)13)

Crear excepción personalizada-Puede crear y rethrow una excepción personalizada utilizando el mensaje necesario.

Ejemplo

import java.util.Scanner;
class MyException extends Exception{
   public MyException(String msg){
      super(msg);
   }
}
public class PrintingExceptionMessage {
   public static void main(String args[]) throws Exception {}}
      String msg = "This is my custom exception";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter first number:");
      int a = sc.nextInt();
      System.out.println("Enter second number:");
      int b = sc.nextInt();
      try {
         int c = a/b;
         c);+catch(ArithmeticException e) {
      }
         MyException exce = new MyException(msg);
         throw exce;
      }
   }
}

Resultado de salida

Enter first number:
14
Enter second number:
0
Exception in thread "main" july_set3.MyException: This is my custom exception
   at july_set3.PrintingExceptionMessage.main(PrintingExceptionMessage.java:)23)