获取异常信息:
通过获取异常信息可以很好的定位异常,找到解决方案。
异常的超类Throwable提供以下获取异常信息方法:
getMessage() 返回对异常的描述
toString() 返回 异常类型 : 异常信息(getMessage()里面的内容)
printStackTrace() 返回异常信息和调用路径,一般IDE里自主抛出的异常信息就是printStackTrace
getStackTrace() 返回异常路径,返回类型为StackTraceElement数组
示例
package chapter12;
public class TestException {
private static int sum(int[] arr) {
int result = 0;
for (int i = 0; i <= arr.length; i++) { // causes ArrayIndexOutOfBoundException
result += arr[i];
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
System.out.println(sum(new int[] {1, 2, 3, 4, 5}));
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("\n" + ex.getMessage());
System.out.println("\n" + ex.toString());
StackTraceElement[] traceElements = ex.getStackTrace();
for (StackTraceElement trace : traceElements) {
System.out.println(trace.getClassName() + " " + trace.getMethodName() + " " + trace.getLineNumber());
}
}
}
}
本例中sum方法会出现数组越界(for循环里)。把这一会出问题的方法放在try语句里。catch语句捕获到该异常。
catch语句里调用printStackTrace(), getMessage(),toString(),getStackTrace()。调用结果如下:
ter12.TestException main 17
备注:
在getStackTrace里我们得到一个StackTraceElement数组,并调用里StackTraceElement类的方法。getClassName返回异常类型,getMethodName返回抛出异常的方法名称,getLineNumber返回该方法具体抛出异常的行数
返回栈里异常信息顺序:先返回直接导致异常的方法,再返回调用异常的方法,以此类推,直到返回到主方法。顺序和调用栈里方法的顺序一致
以下是一个异常处理的示例
package chapter12;
public class CircleWithException {
private double radius;
private static int numberOfObjects = 0;
public CircleWithException() {
this(1.0);
}
public CircleWithException(double newRadius) {
setRadius(newRadius);
numberOfObjects++;
}
public void setRadius(double newRadius) throws IllegalArgumentException {
if (newRadius >= 0) {
radius = newRadius;
} else {
throw new IllegalArgumentException("Radius cannot be negative");
}
}
public static int count() {
return numberOfObjects;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
CircleWithException c1 = new CircleWithException(5);
CircleWithException c2 = new CircleWithException(-5);
CircleWithException c3 = new CircleWithException(0);
} catch (IllegalArgumentException ex) {
System.out.println(ex);
}
System.out.println(count());
}
}
1 setRadius方法会在参数newRadius为负时抛出异常。(注意因为IllegalArgumentException属于Run-time exception,即使不使用throw也会抛出)我们把异常信息自定义为Radius cannot be negative
2 try里面创建c2时触发异常,抛出IllegalArgumentException,被catch接受。catch里直接打出对象,相当于调用toString方法
3 catch部分处理后,接下来System.out.println(count()); 会继续运行。不过try里面创建c3不会运行,因而最后打印出numberOfObjects为1