gpt4 book ai didi

java - 关于try/catch block 中变量范围的问题

转载 作者:行者123 更新时间:2023-11-30 05:58:56 26 4
gpt4 key购买 nike

我有一段代码可能会失败,也可能不会失败,我想在放弃之前尝试 X 次。当它失败时,它会抛出一个特定的异常,所以我认为这样的事情会起作用:

    int retries = 0;
while (retries < MAX_RETRIES) {
failedFlag = false;
try {
//...do some stuff...
logger.info("After commit...");
if (!failedFlag) {
logger.info("Failed flag is false, so breaking out.");
break;
}
} catch (MyException e) {
retries++;
failedFlag = true;
long sleepMillis = MILLIS_TO_SLEEP * retries;
logger.warn("Caught a failure");
logger.warn("Will sleep for " + sleepMillis + "msec and then try again.");
try {
Thread.sleep(sleepMillis);
logger.info("Done sleeping...");
logger.info("Failed flag is " + (failedFlag ? "true" : "false"));
} catch (InterruptedException e1) {
logger.warn("Caught interrupted exception while sleeping. Terminate.");
transaction.rollback();
return;
}
}
}

我遇到的问题是第一个 catch block 中对 failedFlag 所做的更改似乎没有持续存在。失败时,线程会 hibernate ,但是当它醒来并重新进入 try block 时,failedFlag 会恢复为 false?我得到以下日志行:

2010-09-16 17:09:48,448 WARN  [pool-1-thread-1] synchronizer.FlightCreativeSynchronizer - Will sleep for 60000msec and then try again.
...
2010-09-16 17:10:48,449 INFO [pool-1-thread-1] synchronizer.FlightCreativeSynchronizer - Done sleeping...
2010-09-16 17:10:48,450 INFO [pool-1-thread-1] synchronizer.FlightCreativeSynchronizer - Failed flag is true
2010-09-16 17:10:48,453 INFO [pool-1-thread-1] synchronizer.FlightCreativeSynchronizer - After commit...
2010-09-16 17:10:48,453 INFO [pool-1-thread-1] synchronizer.FlightCreativeSynchronizer - Failed flag is false, so breaking out.

这里有点令人困惑...局部变量是否不受 catch block 中所做的更改的影响?

最佳答案

您在 while 循环的顶部将 failedFlag 设置为 false。

关于java - 关于try/catch block 中变量范围的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3729328/

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