Java语言的异常类Exception包含着异常的所有信息。java
现设异常的实例名为ex,全部的异常都是一个除以0的表达式(int i = 1 / 0)所触发的:app
一、经过ex.getMessage()能够获取异常信息,如函数
/ by zero
二、经过ex.toString()能够获取异常类型和异常信息,如测试
java.lang.ArithmeticException: / by zero
三、经过ex.printStackTrace()能够直接在控制台打印异常的所有信息(包括堆栈),但该函数最好不要直接调用无参数的版本,由于这样会让控制台显示出现错乱。调用printStackTrace时,经过以下方法调用:ui
StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); ex.printStackTrace(printWriter); System.out.println(stringWriter.toString());
使用此方法,控制台输出的内容为:code
java.lang.ArithmeticException: / by zero at ExceptionTest.exec3(ExceptionTest.java:31) at ExceptionTest.exec2(ExceptionTest.java:23) at ExceptionTest.exec1(ExceptionTest.java:15) at ExceptionTest.main(ExceptionTest.java:39)
若是使用的是Eclipse的控制台,异常类名和指明行数的错误堆栈都会生成相应的跳转连接。orm
四、经过ex.getStackTrace()能够获取堆栈信息,这是 ex.printStackTrace() 外的另外一种获取异常堆栈信息的方法。经过此方法能够定制化输出堆栈信息。ip
System.out.println(ex.getClass().getName() + ": " + ex.getMessage()); StringBuilder sbException = new StringBuilder(); for (StackTraceElement ele : ex.getStackTrace()) { sbException.append(MessageFormat.format("\tat {0}.{1}({2}:{3})\n", ele.getClassName(), ele.getMethodName(), ele.getFileName(), ele.getLineNumber()));; } System.out.println(sbException);
打印出的异常堆栈为:get
java.lang.ArithmeticException: / by zero at ExceptionTest.exec3(ExceptionTest.java:31) at ExceptionTest.exec2(ExceptionTest.java:23) at ExceptionTest.exec1(ExceptionTest.java:15) at ExceptionTest.main(ExceptionTest.java:39)
最后列一下完整的Java代码:string
import java.io.PrintWriter; import java.io.StringWriter; import java.text.MessageFormat; /** * 异常打印测试 * @文件名称 ExceptionTest.java * @文件做者 Tsybius2014 * @建立时间 2016年5月13日 下午6:14:08 */ public class ExceptionTest { /** 第一层函数 */ public static void exec1() { try { exec2(); } catch (Exception ex) { throw ex; } } /** 第二层函数 */ public static void exec2() { try { exec3(); } catch (Exception ex) { throw ex; } } /** 第三层函数 */ public static void exec3() { try { int i = 1 / 0; } catch (Exception ex) { throw ex; } } /** 主函数 */ public static void main(String[] args) { try { exec1(); } catch (Exception ex) { System.out.println("--- getMessage ---"); System.out.println(ex.getMessage()); System.out.println(); System.out.println("--- toString ---"); System.out.println(ex.toString()); System.out.println(); System.out.println("--- printStackTrace ---"); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); ex.printStackTrace(printWriter); System.out.println(stringWriter.toString()); System.out.println(); System.out.println("--- printStackTrace DIY ---"); System.out.println(ex.getClass().getName() + ": " + ex.getMessage()); StringBuilder sbException = new StringBuilder(); for (StackTraceElement ele : ex.getStackTrace()) { sbException.append(MessageFormat.format("\tat {0}.{1}({2}:{3})\n", ele.getClassName(), ele.getMethodName(), ele.getFileName(), ele.getLineNumber()));; } System.out.println(sbException); } } }
控制台输出结果以下:
END