自定义异常
public MyException(String msg) { //调用父类构造方法传递“异常信息”
super(msg);
}
}
public class ExceptionTest {
public static void Arithmetic() throws MyException {
//静态类Arithmetic需向上抛出自定义异常,目的是交给调用者处理
int a = 10, b = 0;
if (b == 0) { //满足该条件则执行以下语句
System.out.println("b的值不符合条件,所以我要抛出算术异常...");
throw new MyException("算数异常!"); //抛出一个自定义异常,异常信息为“算数异常”
}
System.out.println(a / b); //程序若执行到此步则说明没有异常
}
public static void ArrayIndexOfBounds(int[] arr) throws MyException {
//静态类ArrayIndexOfBounds需向上抛出自定义异常,目的是交给调用者处理
System.out.print("打印数组的各项值:");
for (int i = 0; i <= arr.length; i++) {
if (i == arr.length) { //满足该条件则执行以下语句
throw new MyException("数组下标越界异常!"); //抛出一个自定义异常,异常信息为“数组下标越界异常”
}
System.out.print(arr[i] + " "); //程序若执行到此步则说明没有异常
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {23, 11, 45, 48, 33};
/*若要调用一个向上抛出了异常的方法就必须得进行两种异常处理方式其中的一种,否则会造成编译时异常,编译器不会通过
* 1 在方法声明的位置上使用throws关键字接着向上抛出异常,但总要有人处理,若是main方法向上抛出异常,
* 则会交给JVM处理,结果只有一种:终止该程序。
* 2 使用try...catch语句捕捉该异常
* 我们在这里就使用try...catch语句对有异常的语句进行捕捉
*/
try {
System.out.println("调用Arithmetic()方法...");
Arithmetic();
} catch (MyException e) {
System.out.println("捕捉到算术异常...");
System.out.println(e.getMessage());
}
System.out.println();
try {
System.out.println("调用ArrayIndexOfBounds()方法...");
ArrayIndexOfBounds(arr);
} catch (MyException e) {
System.out.println("捕捉到算术异常...");
System.out.println(e.getMessage());
}
System.out.println("Exit..."); //程序退出...
}
}

浙公网安备 33010602011771号