如何使用mult-catch子句?

Vba*_*bey 0 java exception try-catch

class Demo{
public static void main(String args[]){
    int x=3,n=5,d=0;
    int ar[]=new int[3];
    String name="Neno";

    System.out.println("Start main");
    try{
        ar[x]=name.charAt(n)/d; //n=5
    }catch(StringIndexOutOfBoundsException e){
        System.out.println("String index Error");
    }catch(RuntimeException e){
        System.out.println("Any runtime Error");
    }catch(ArrayIndexOutOfBoundsException e){
        System.out.println("Array index Error");
    }catch(ArithmeticException e){
        System.out.println("Arithmetic Error");
    }

    System.out.println("End   main");
}
}
Run Code Online (Sandbox Code Playgroud)

我使用此代码来过滤一些异常,但代码中存在错误.它说删除的追赶条款ArrayIndexOutOfBoundsArithmeticException.是因为错误弹出的catch-clauses的顺序?当我改变这样的顺序时......

class Demo{
public static void main(String args[]){
    int x=3,n=5,d=0;
    int ar[]=new int[3];
    String name="Niroth";

    System.out.println("Start main");
    try{
        ar[x]=name.charAt(n)/d; //n=5
    }catch(StringIndexOutOfBoundsException e){
        System.out.println("String index Error");
    }catch(ArrayIndexOutOfBoundsException e){
        System.out.println("Array index Error");
    }catch(ArithmeticException e){
        System.out.println("Arithmetic Error");
    }catch(RuntimeException e){
        System.out.println("Any runtime Error");
    }catch(Exception e){
        System.out.println("Any Error");
    }

    System.out.println("End   main");
}
}
Run Code Online (Sandbox Code Playgroud)

这个顺序没有错误.谁能解释一下这个问题的原因?

roc*_*boy 5

捕获异常就像是一个接一个地放置的桶.你必须在最后一个中解决更广泛的问题.希望以下图表有所帮助:

错误:

 \                           /
  \_____RuntimeException____/

      \                  /
       \__AIOBException_/        //ArrayIndexOutOfBounds

      \                 /
       \__AriException_/        //ArithmeticException
Run Code Online (Sandbox Code Playgroud)

正确:

      \                  /
       \__AIOBException_/        //ArrayIndexOutOfBounds

      \                 /
       \__AriException_/        //ArithmeticException 

 \                           /
  \_____RuntimeException____/
Run Code Online (Sandbox Code Playgroud)

  • 对ASCII艺术的笑脸和好的比喻:-) (4认同)