java for循环 try catch

编程入门 行业动态 更新时间:2024-10-28 02:33:56

<a href=https://www.elefans.com/category/jswz/34/1770091.html style=java for循环 try catch"/>

java for循环 try catch

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循环都会执行,当遇到异常时,抛出异常继续执行;放在外面,当遇到异常时,抛出异常,后面的循环就会终止,并不会执行。

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

更多推荐

java for循环 try catch

本文发布于:2024-02-26 05:02:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1701431.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:java   catch

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!