捕获并处理各种类型的异常
1.编写ExceptionTest.java 程序文件,源代码如下。
package Myjava;
import java.io.*;
public class ExceptionTest{
public static void main(String args[]) {
for(int i = 0; i < 4;i++) {
int k;
try {
switch( i ) {
case 0:
int zero = 0;
k = 911 / zero;
break;
case 1:
int b[ ] = null;
k = b[0];
break;
case 2:
int c[ ] = new int[2];
k = c[9];
break;
case 3:
char ch = "abc".charAt(99);
break;
}
}catch(Exception e) {
System.out.println("\nTestcase #" + i + "\n");
System.out.println(e);
}
}
}
}
2. 编译、运行
Testcase#0
java.lang.ArithmeticException: / by zero
Testcase#1
java.lang.NullPointerException
Testcase#2
java.lang.ArrayIndexOutOfBoundsException: 9
Testcase#3
java.lang.StringIndexOutOfBoundsException: String index out of range: 99
3.根据运行结果,请在实验报告中说明程序运行中总共捕捉了几个异常,并指出每个异常各自属于哪种类型的异常?
4个异常。
java.lang.ArithmeticException
java.lang.NullPointerException
java.lang.ArrayIndexOutOfBoundsException
java.lang.StringIndexOutOfBoundsException。