当for循环遇上try-catch

首先是不建议在循环体内部进行try-catch操作,效率会非常低,这里仅仅是测试这种情况,具体的业务场景建议还是不要在循环里try-catch

@Test
    public void forThrow(){
        final int size = 6;
        for (int i=0; i<size; i++){

            if(i > 3){
                throw new IllegalArgumentException(i+" is greater than 3");
            }

            System.out.println(i);
        }
    }

Java中for循环中的的try-catch

上面执行了一个for循环,当i大于5就抛出异常,这里由于没有捕获异常,程序直接终止。 下面来看看捕获异常后的结果
@Test
    public void forThrowException(){
        final int size = 6;
        for (int i=0; i<size; i++){
            try {
                if(i > 3){
                    throw new IllegalArgumentException(i+" is greater than 3");
                }
            }catch (IllegalArgumentException e){
                e.printStackTrace();
            }
            System.out.println(i);
        }
    }

Java中for循环中的的try-catch

由于内部捕获了异常,程序打印出堆栈,程序没有终止,直到正常运行结束。
进行数据运算时,如果抛出了异常,数据的值会不会被改变呢?

@Test
    public void forExceptionEditValue(){
        final int size = 6;
        int temp = 12345;
        for (int i=0; i<size; i++){
            try {
                temp = i / 0;
            }catch (ArithmeticException e){
                e.printStackTrace();
            }
            System.out.println("i = "+i+", temp = "+temp);
        }
    }

Java中for循环中的的try-catch

可以看到,当想要改变temp的值的时候,由于数据运算抛出了异常,temp的值并没有改变!

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-21
  • 2022-12-23
  • 2021-11-04
  • 2022-01-24
  • 2021-08-02
猜你喜欢
  • 2021-09-21
  • 2022-03-01
  • 2021-12-11
  • 2021-06-20
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案