Java:我如何编写try-catch-repeat块?

Leg*_*end 16 java exception-handling exception try-catch

我知道这样做的反制方法.我想知道是否有一个很好的和紧凑的方式来做到这一点.

oxb*_*kes 28

传奇 - 你的答案可以改进; 因为如果你失败了numTries,你就会吞下这个例外.好多了:

while (true) {
  try {
    //
    break;
  } catch (Exception e ) {
    if (--numTries == 0) throw e;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果(--numTries == 0)非常危险.如果是0或更低的开始怎么办?我宁愿<1 (7认同)

Leg*_*end 5

我见过几种方法,但我使用以下方法:

int numtries = 3;
while(numtries-- != 0)
   try {
        ...
        break;
   } catch(Exception e) {
        continue;
   }
}
Run Code Online (Sandbox Code Playgroud)

这可能不是最好的方法.如果您有任何其他建议,请将它们放在这里.

编辑:oxbow_lakes提出了一个更好的方法.请看一下......

  • @Legend - 我想如果你看看我的答案,你会发现你的方法存在缺陷 (2认同)