Java 异常处理

来源:互联网 发布:好声音网络主播 编辑:程序博客网 时间:2024/06/05 15:14

异常处理中,catch的参数类型父类子类关系

  • 在异常处理中,若try中的代码可能产生多种异常则可以对应多个catch语句,若catch中的参数类型有父类子类关系,此时应该将父类放在后面,子类放在前面

    如下代码:

public class Test {    public static void main(String[] args) {        try{                    int x=0;                    int y=5/x;                }        catch(ArithmeticException ae){                    System.out.println("Arithmetic Exception");                   }          catch(Exception e){                   System.out.println("Exception");                    }           System.out.println("finished");            }}
输出结果为:Arithmetic Exceptionfinished
  • 在这里解释:
    catch(ArithmeticException ae) 和 catch(Exception e) 的位置调换,则程序报错,因为Exception e 是 ArithmeticException ae 的父类。当子父类在子类的前面是,抛出的异常已经被父类处理了,后面的子类就不能接收异常。
0 0