天天看點

Java程式設計GOTO語句妙用

GOTO語句的使用

小文法,大妙用

場景:當參數1執行失敗,報出特定異常的時候,需要調整相應參數,再重新執行

public class MainTest {

    public static void main(String[] args) throws Exception {
        int param = 1;
        boolean isFinish = false;
        looper:
        while (!isFinish) {
            try {
                method(param);
                isFinish = true;
            } catch (Exception e) {
                // 報110異常,調整參數重試
                if (e.getMessage().equals("110") && param == 1) {
                    System.out.println(String.format("參數%s執行失敗,調整參數重試", param));
                    param = 2;
                    continue looper;
                }
                // 避免死循環,如果抛出異常,則不用這一句
//                isFinish = true;
                throw e;
            }
        }
    }

    public static void method(int param) throws Exception {
        switch (param) {
            case 1:
                throw new Exception("110");
            case 2:
                System.out.println(String.format("參數%s執行成功", param));
        }
    }
}