打破一个循环,其中有一个try-catch块

Ill*_*lep 0 java

我有一个While循环,并在其中有一个try catch块.如何在catch语句中添加break语句来打破while循环.我不想使用DO-WHILE循环,因为我只需要几分钟来提交我的代码,而且我不想通过进行更改来破坏程序.但是,稍后我将考虑使用DO-WHILE语句更改代码.

while (true) {
try {
// something here
} catch (Exception e) {

// I need to break the forever while loop here
}
}
Run Code Online (Sandbox Code Playgroud)

chr*_*her 8

try {
// something here
    while (true) {
    // While body here.
    }
} catch (Exception e) {

// I need to break the forever while loop here
}
} 
Run Code Online (Sandbox Code Playgroud)

您可以在try catch体内移动while循环.这将以编程方式完全相同,但所有错误都将被捕获,并且不需要执行任何操作.这看起来更好,并且更具语义感.

而且,只需break;在catch块中添加单词,它就会停止循环的运行.

  • 也许他不想在try-catch块中使用while循环.例如,如果他只需要try/catch来进行某种读/写/数据库访问.在这种情况下,在catch块中添加break听起来就像是最好的解决方案. (2认同)