Java异常处理实战二
一 异常对象ex的使用
1 代码
public class excepObject
{
public static void main( String[] args )
{
try
{
int arr[] = new int[5];
arr[10] = 7;
}
catch( ArrayIndexOutOfBoundsException ex )
{
System.out.println( "数组超出绑定范围!" );
System.out.println( "异常:" + ex ); // 显示异常对象e的内容
// ex.printStackTrace();
}
System.out.println( "main()方法结束!" );
}
}
2 运行
数组超出绑定范围!
异常:java.lang.ArrayIndexOutOfBoundsException: 10
main()方法结束!
二 通过多个catch捕获异常
1 代码
public class arrayException {
public static void main( String args[] ) {
System.out.println("-----A、计算开始之前");
try {
int arr[] = new int[5];
;
arr[0] = 3;
arr[1] = 6;
arr[1] = 0; // 除数为0,有异常
arr[10] = 7; // 数组下标越界,有异常
int result = arr[0] / arr[1];
System.out.println("------B、除法计算结果:" + result);
} catch (ArithmeticException ex) {
ex.printStackTrace();
} catch (ArrayIndexOutOfBoundsException ex) {
ex.printStackTrace();
} finally {
System.out.println("-----此处不管是否出错,都会执行!!!");
}
System.out.println("-----C、计算结束之后。");
}
}
2 运行
-----A、计算开始之前
java.lang.ArrayIndexOutOfBoundsException: 10
at arrayException.main(arrayException.java:19)
-----此处不管是否出错,都会执行!!!
-----C、计算结束之后。
还没有评论,来说两句吧...