java for循环 try catch_trycatch放在for循环的里面还是外面好

try放在for循环里面和外面的区别是什么呢?先看看下面的代码的区别:

public class Test {

public void test1(){

for (int count = 0; count < 6; count++) {

try {

int x;

if (count == 3)

x = 1 / 0;

else{

x = count;

System.out.println(x);

}

} catch(Exception e){

System.out.println("异常");

}

}

}

public void test2(){

try {

for (int count = 0; count < 6; count++) {

int x;

if (count == 3)

x = 1 / 0;

else{

x = count;

System.out.println(x);

}

}

} catch (Exception e) {

System.out.println("异常");

}

}

public static void main(String[] args) throws Exception {

Test te = new Test();

te.test1();

System.out.println("------------------------");

te.test2();

}

}

结果:

0

1

2

异常

4

5

------------------------

0

1

2

异常

总结:try放在for循环的里面所有的for循环都会执行,当遇到异常时,抛出异常继续执行;放在外面,当遇到异常时,抛出异常,后面的循环就会终止,并不会执行。

对于放到里面还是外面,有时候还看自己的选择,一般建议放到里面比较好。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值