gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:01:36 32 4
gpt4 key购买 nike

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

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

    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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com