java - 发生错误时重试

标签 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");
        }
    }
}

我该怎么做?

最佳答案

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

关于java - 发生错误时重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14253449/

相关文章:

java - JSF 2.0 - bean 作用域的可能性

java - Jsoup element.class.class selcet 方法返回 null

Javascript 函数在循环中使用最后已知的参数?

javascript - 将图像像素数据转换为坐标数组

java - 从三点定义曲线

java - 泛型和参数化构造函数

Ruby 哨兵循环未按预期工作(七周七种语言)

javascript - 在 fetch() 函数中捕获错误

excel - AGGREGATE未按预期处理错误

php - 引用 - 这个错误在 PHP 中意味着什么?