这个程序中越界异常和算数异常都有,但是程序在检测到越界异常后不会继续执行 所以算数异常不会打印
这些异常都是Except的子类,如果在第一个异常就写
catch (Exception e) { System.out.println("有问题"); }这样只要有异常就会被捕获 后面是不会编译通过的,只有把父类写在最后,才不会报错
不自己写异常也是可以的,通过函数中的对象e来调用异常原因
catch (ArrayIndexOutOfBoundsException e) // 传入一个对象作为参数 { System.out.println(e.getMessage()); }①方法中抛出异常
public class test { public static void function() throws ArrayIndexOutOfBoundsException, ArithmeticException { int a[] = {1, 2, 3}; int sum = 0; int n = 0; // 分母 double ave = 0; for(int i = 0; i <= 3; i++) sum += a[i]; ave = sum / n; } public static void main(String args[]) { try { function(); } catch (NumberFormatException e) { System.out.println("非数据类型不能转换。"); } catch (ArrayIndexOutOfBoundsException e) // 传入一个对象作为参数 { System.out.println("数组越界"); } catch(ArithmeticException e ) { System.out.println("分母为0"); } } }在这个类中,定义一个方法function,利用关键字throws抛出可能的多个异常,然后在主函数中捕获这个异常,然后进行相应的操作
②自己在程序中抛出异常 关键字throw
public class test { public static void main(String args[]) { int a[] = {1, 2, 3}; int sum = 0; int n = 0; // 分母 double ave = 0; try { if(a[1] == 2) throw new Exception("随便写的"); } catch(Exception e) { System.out.println(e.getMessage()); } } }本程序中是可以抛出这个异常的
我们这个是程序员自己主动抛出的异常 所以要在try里面主动抛出,最后在catch中捕获
我们首先定义一个异常类,继承Except 在这个类中定义异常信息message
在Bank类中,我们用判断语句,如果在特定情况下发生异常,就抛出异常
public void income(int in, int out) throws BankError // 主动抛出自己写的异常 { if(in <= 0 || out >= 0 || in + out <= 0) // 发现异常 throw new BankError(in, out);最后捕获异常 输出异常信息
这个例子中,在抛出自己写的异常时,要用throws在方法后声明可能出现的自定义异常,不然会报错。 抛出异常,其实也就抛出了一个被构造的类,捕获的时候可以使用这个被抛出的类调用其中的异常信息