多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;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM