1

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

我怎样才能做到这一点?

4

1 回答 1

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");
于 2013-01-10T08:20:59.057 回答