如何处理 Java 中的异常方法
问题描述
如何处理异常方法?
解决方案
此示例显示如何使用 System 类的 System.err.println() 方法来处理异常方法。
public class NewClass { public static void main(String[] args) { try { throw new Exception("My Exception"); } catch (Exception e) { System.err.println("Caught Exception"); System.err.println("getMessage():" + e.getMessage()); System.err.println("getLocalizedMessage():" + e.getLocalizedMessage()); System.err.println("toString():" + e); System.err.println("printStackTrace():"); e.printStackTrace(); } } }
结果
上述代码示例将产生以下结果。
Caught Exception getMassage(): My Exception gatLocalisedMessage(): My Exception toString():java.lang.Exception: My Exception print StackTrace(): java.lang.Exception: My Exception at ExceptionMethods.main(ExceptionMeyhods.java:12)
java_exceptions.html