多catch块的代码优化

一、多catch块的代码优化

在写代码时,多行存在不同的异常,使用try catch的话,习惯性的是有多个catch,如下所示:

注意到warning,文字描述如下:

Reports identical catch sections in try blocks under JDK 7. A quickfix is available to collapse the sections into a multi-catch section.
This inspection only reports if the project or module is configured to use a language level of 7.0 or higher.

 大概意思是再try的代码块中,存在多个catch块结构时,如果使用的是JDK 7及以上,把这些catch块进行折叠到一个中更高效,如下所示:

 

二、&&、&、|、||的区别

另外,扩展一下&&、&、|、||的区别:简单来说就是&&,||有短路功能,而&、|没有,所以&&、||的性能更佳,测试代码如下:

    @Test
    public void test() {
        int c = 2;
        if (c == b() | c == a()) {
            // 会打印
            // b() 返回值: 2
            // a() 返回值: 1
            System.out.println("|  c = " + c);
        }
        System.out.println("|---- test end");


        if (c == b() || c == a()) {
            // 会打印
            // b() 返回值: 2
            System.out.println("||  c = " + c);
        }
        System.out.println("||---- test end");


        if (c == a() & c == b()) {
            // 会打印
            // a() 返回值: 1
            // b() 返回值: 2
            System.out.println("&  c = " + c);
        }
        System.out.println("&---- test end");


        if (c == a() && c == b()) {
            // 会打印
            // a() 返回值: 1
            System.out.println("&&  c = " + c);
        }
        System.out.println("&&---- test end");

    }

    public int a() {
        System.out.println("a() 返回值: " + 1);
        return 1;
    }

    public int b() {
        System.out.println("b() 返回值: " + 2);
        return 2;
    }

 

转载于:https://www.cnblogs.com/miaoying/p/10845665.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值