发生错误时,我想尝试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");
        }
    }
}

我怎样才能做到这一点?

最佳答案

使用一个循环,循环使用已完成的值[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");

10-04 21:11
查看更多