发生错误时再试一次

时间:2013-01-10 08:18:12

标签: java loops error-handling

我想在发生错误时尝试3次。 到目前为止我做了什么......

public class TryTest {

    public static void main(String[] args) {
        TryTest test = new TryTest();
        test.tryThis();
    }

    public void tryThis() {
        int a = 10;
        int x = 0;
        int count = 1;
        try {
            System.out.println("Test " + count);
            a = a / x;
            System.out.println("Success !");
        } catch (Exception e) {
            if (count <= 3) {
                // I want to try again with new x value
                count++;
                x++;
            }
            System.out.println("ERROR:\t" + e);
        } finally {
            System.out.println("Finish");
        }
    }
}

我该怎么做?

1 个答案:

答案 0 :(得分:6)

使用一个循环,循环使用你有一个完成值[0,3]

for(int i = 0; i < 3; i++) {
    try {
        System.out.println("Test " + count);
        int a = 10 / i;
        System.out.println("Success !");
        break;

    } catch (Exception e) {
        System.out.println("ERROR:\t" + e);
    }
 }
 System.out.println("Finish");