如何在Java中打印自定义消息而不是ErrorStackTrace?
例外是程序执行期间发生的问题(运行时错误)。当发生异常时,程序会突然终止,并且生成异常的行之后的代码将永远不会执行。
打印异常消息
您可以使用从Throwable类继承的以下方法之一在Java中打印异常消息。
printStackTrace()-此方法将回溯打印到标准错误流。
getMessage()-此方法返回当前可抛出对象的详细消息字符串。
toString()-此消息显示当前可抛出对象的简短描述。
示例
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; System.out.println("The result is: "+c); }catch(ArithmeticException e) { System.out.println("Output of printStackTrace() method: "); e.printStackTrace(); System.out.println(" "); System.out.println("Output of getMessage() method: "); System.out.println(e.getMessage()); System.out.println(" "); System.out.println("Output of toString() method: "); System.out.println(e.toString()); } } }
输出结果
Enter first number: 10 Enter second number: 0 Output of printStackTrace() method: java.lang.ArithmeticException: / by zero Output of getMessage() method: / by zero Output of toString() method: java.lang.ArithmeticException: / by zero at PrintingExceptionMessage.main(PrintingExceptionMessage.java:11)
打印自定义异常消息
重新抛出异常-您可以使用new关键字重新抛出catch块中捕获的异常,在执行此操作时,您需要将catched异常对象与代表消息的String一起传递,然后显示已传递的消息原始消息。
示例
import java.util.Scanner; public class PrintingExceptionMessage { public static void main(String args[]) throws Exception { String msg = "This is my custom message"; 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; System.out.println("The result is: "+c); }catch(ArithmeticException e) { throw new Exception("CoustomMessage: "+msg, e); } } }
输出结果
Enter first number: 25 Enter second number: 0 Exception in thread "main" java.lang.Exception: CoustomMessage: This is my custom message at july_set3.PrintingExceptionMessage.main(PrintingExceptionMessage.java:16) Caused by: java.lang.ArithmeticException: / by zero at july_set3.PrintingExceptionMessage.main(PrintingExceptionMessage.java:13)
创建自定义例外-您可以使用所需消息创建并重新抛出自定义例外。
示例
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; System.out.println("The result is: "+c); }catch(ArithmeticException e) { MyException exce = new MyException(msg); throw exce; } } }
输出结果
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)