public class Finally {
public static void main(String[] args) {
int i=0;

String greetings[]={"Hello word!","Hello word!!","Hello word!!!"};
while(i<4) {
try {
System.out.println(greetings[i]);
i++;//无线循环
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("数组下标越界");
}finally{
System.out.println("--------");
}
}
}}为什么这个函数会无限循环?把System.out.println(greetings[i]);i++;这两句换为System.out.println(greetings[i++]);为什么就不会无限循环呢?

解决方案 »

  1.   

    public class Finally {
    public static void main(String[] args) {
    int i=0;String greetings[]={"Hello word!","Hello word!!","Hello word!!!"};
    while(i<4) {
    try {
    System.out.println(greetings[i]);}catch(ArrayIndexOutOfBoundsException e){
    System.out.println("数组下标越界");
    }finally{
    System.out.println("--------");
    i++;
    }
    }
    }}
      

  2.   

    因为System.out.println(greetings[i]);
    抛出了异常 直接进入catch
    i没有自加
    所以无法跳出循环而System.out.println(greetings[i++]);虽然抛出了异常
    但是i完成了自加
    所以能跳出循环了
      

  3.   

    肯定的,你把异常处理语句写在循环里面了,当I=3时,语句执行到System.out.println(greetings[i])抛异常就直接跳到异常处理去了而没有进行i步进的操作。于是一直在i=3这写了i++就会执行步进的操作