Java 打破一个while循环,那里有一个try-catch块
我有一个While循环,其中有一个try-catch块。如何在catch语句中添加break语句来中断while循环。我不想使用DO-WHILE循环,因为我只有几分钟的时间来提交代码,而且我不想通过更改来破坏程序。但是,稍后我会考虑使用do-Trand语句来更改代码。Java 打破一个while循环,那里有一个try-catch块,java,Java,我有一个While循环,其中有一个try-catch块。如何在catch语句中添加break语句来中断while循环。我不想使用DO-WHILE循环,因为我只有几分钟的时间来提交代码,而且我不想通过更改来破坏程序。但是,稍后我会考虑使用do-Trand语句来更改代码。 while (true) { try { // something here } catch (Exception e) { // I need to break the forever while loop here } }
while (true) {
try {
// something here
} catch (Exception e) {
// I need to break the forever while loop here
}
}
在catch块中放一个break语句
try {
// something here
while (true) {
// While body here.
}
} catch (Exception e) {
// I need to break the forever while loop here
}
}
可以在try-catch主体内移动while循环。这将以完全相同的编程方式执行,但所有错误都将被捕获,无需执行一段时间。这看起来好得多,而且更有语义意义
此外,只需添加单词break;在catch块中,它将停止循环的运行。除非catch子句中有另一个奇怪的循环,否则使用break try-catch不是循环,因此中断会影响第一个包含循环,这似乎是while。它会起作用 但您应该做的是退出循环,因为您遇到了如下异常:
try {
while (true) {
// something here
}
} catch (Exception e) {
// Do whatever in the catch
}
您可以在while循环中引入一个最初为true的布尔变量,并在try或catch语句中的任何位置将其设置为false。这样,即使给定的循环中有嵌套的循环,也可以打断该循环
boolean notDone = true;
while(notDone) {
try {
// something here
} catch (Exception e) {
// I need to break the forever while loop here
notDone = false;
}
您可以使用非自然使用反转版本,而使用完成布尔值。这导致您需要在每次迭代的while循环中调用invert。这是在较小的性能和更高的代码可读性之间的折衷。只需命名您的循环并打破它 比如说
Lable:
while (true) {
try {
// something here
} catch (Exception e) {
// I need to break the forever while loop here
break Lable;
}
}
有多种方法 方法1-通过反转While条件变量 方法2-使用break语句 方法3-将挡块移到外侧 如何在catch语句中添加break语句来中断while循环 就这么做吧。在catch语句中添加break语句。它将打破while循环
这不是一个真正的问题。break???这行吗?也许他不想在try-catch块中使用while循环。例如,如果他只需要try/catch进行某种读/写/数据库访问。在这种情况下,在catch块中添加break听起来是最好的解决方案。此外,try-catch块中的whiletrue循环无论以何种方式旋转,对我来说都不好看:-它不会“以完全相同的编程方式运行”。这完全取决于挡块内部的内容。解决这个非问题不需要代码运动。什么是标签。像C++@Illep中的goto语句这样的循环检查,即使它存在于Java中,也不是一个好的实践。使用Goto语句意味着在您的逻辑中有不正确的地方。
boolean notDone = true;
while(notDone) {
try {
// something here
} catch (Exception e) {
notDone = false;
}
}
while(notDone) {
try {
// something here
} catch (Exception e) {
break;
}
}
try {
while(notDone) {
}
} catch (Exception e) {
}