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

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

    
    
  • 相关阅读:
    d3js 获取元素以及设置属性
    javascript 转义函数
    es6 对象浅拷贝的2种方法
    SwitchyOmega 代理设置
    table 设置边框
    Highcharts 配置选项详细说明
    windows环境下生成ssh keys
    vue 给组件绑定原生事件
    Vue 字面量语法 vs 动态语法
    Vue 2.0 v-for 响应式key, index及item.id参数对v-bind:key值造成差异研究
  • 原文地址:https://www.cnblogs.com/jialin1402/p/7380033.html
Copyright © 2011-2022 走看看