c# - 抛出异常时执行某事的最佳方式(模式)

标签 c# exception for-loop try-catch

下面的代码显示了尝试封装一个逻辑以在捕获异常时重新运行某些东西。

是否存在模式或其他方式来做到这一点?或者您会对该代码提出哪些改进建议?

    public static void DoWhileFailing(int triesAmount, int pauseAmongTries, Action codeToTryRun) {
        bool passed = false;
        Exception lastException = null;

        for (int i = 0; !passed && i < triesAmount; i++) {
            try {
                if (i > 0) {
                    Thread.Sleep(pauseAmongTries);
                }
                codeToTryRun();
                passed = true;
            } catch(Exception e) {
                lastException = e;
            }
        }

        if (!passed && lastException != null) {
            throw new Exception(String.Format("Something failed more than {0} times. That is the last exception catched.", triesAmount), lastException);
        }
    }

最佳答案

我会重写它以消除一些变量,但总的来说你的代码没问题:

public static void DoWhileFailing(int triesAmount, int pauseAmongTries, Action codeToTryRun) {
    if (triesAmount<= 0) {
        throw new ArgumentException("triesAmount");
    }
    Exception ex = null;
    for (int i = 0; i < triesAmount; i++) {
        try {
            codeToTryRun();
            return;
        } catch(Exception e) {
            ex = e;
        }
        Thread.Sleep(pauseAmongTries);
    }
    throw new Exception(String.Format("Something failed more than {0} times. That is the last exception catched.", triesAmount, ex);
}

关于c# - 抛出异常时执行某事的最佳方式(模式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13975730/

相关文章:

c# - 任务在哪个核心上运行?

c# - Xamarin - Android - Visual Studio - 应用程序无法启动

c# - N2 内容管理系统 : Are nested collections of ContentItems possible?

java - 为什么在这种情况下需要catch IOException

c++ - 使用空指针参数和不可能的后置条件构造标准异常

java - For 循环不终止

c# - 如何使用 ASP.NET Core 仅在一种方法中获得所需的依赖项

c# - 如何在调用其他构造函数之前抛出 ArgumentNullException

java - 如何编写一个输出三角形数字的java程序?

c - 对带有数组和嵌套 For 循环的程序中特定语句的作用感到困惑