我發現我不會使用return和continue注意細節才能讓bug無處藏身

 scoket循環監聽某一個端口,時刻準備接受客戶端的請求,所有要使用where循環。但裏面會遇到接受報文的異常,怎麼處理?

項目已經上線2個多月了,突然出現了一個異常,整個監聽就結束了?很奇怪。

最後發現問題就在return上。

test1:return如果遇到異常,where循環就直接結束了,監聽也就結束了。這個錯誤之前沒發現,因爲測試的時候發的測試報文僅僅是數據錯誤,並沒有考慮其他因素(如數據格式錯誤,不符合接收規則等)。

test2:continue如果遇到異常,僅僅會結束本次循環,並不會影響到where下次循環,所有,監聽程序繼續執行。

test3:break只能用在循環中,直接結束整個循環。

public class TestDemo {
    
    public static void main(String[] args) {
        test1();
        test2();
        test3();
    }

    public static void test1(){
        while (true){
            System.out.println("test1->---  scoket循環監聽執行了"+new Date());
            try{
                Thread.sleep(2000);
                //製造異常
               int a=1/0;
            }catch (Exception e){
                System.out.println(e);
                return;
            }
        }
    }


    public static void test2(){
         while (true){
            System.out.println("test2->---  scoket循環監聽執行了"+new Date());
            try{
                Thread.sleep(2000);
                //製造異常
               int a=1/0;
            }catch (Exception e){
                System.out.println(e);
                continue;
            }
        }
    }

     public static void test3(){
         while (true){
            System.out.println("test3->---  scoket循環監聽執行了"+new Date());
            try{
                 Thread.sleep(2000);
                //製造異常
               int a=1/0;
            }catch (Exception e){
                System.out.println(e);
                break;
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章