gpt4 book ai didi

java - 在不中断 java 循环的情况下抛出异常

转载 作者:行者123 更新时间:2023-11-30 06:10:39 24 4
gpt4 key购买 nike

我需要在 java 内部循环中处理自定义异常,所以我抛出了新的自定义异常,但它打破了循环。我们如何在不中断循环的情况下设法抛出循环。这是我的代码

    for (int i = 0; i < j; i++) {
File currFile = arrayOfFile1[i];
if (currFile.isFile()) {
if (currFile.exists()) {
try {
String fileName = currFile.getName();
if (fileName.startsWith("~$")) {
continue;
} else {
if ((fileName.endsWith(".xlsx")) || (fileName.endsWith(".xls"))) {
if (fileName.endsWith("_arch.xlsx") || fileName.endsWith("_arch.xls")) {
continue;
}
try {
IDSOutputGenerator.generateOutput(currFile.getAbsolutePath(), "", outputType,
false);
} catch (CheckErrorHandle e) {
throw new CheckErrorHandle();
}
}
else if (fileName.endsWith(".xml")) {
try {
IDSOutputGenerator.generateOutput(currFile.getAbsolutePath(), "", outputType,
false);
} catch (CheckErrorHandle e) {
throw new CheckErrorHandle();
}

} else {
throw new CheckErrorHandle(currFile.getAbsolutePath(), "File type not supported");
}
}
} catch (CheckErrorHandle e) {
throw new CheckErrorHandle();
} catch (Exception e) {
throw new CheckErrorHandle("", e.getMessage());
}
} else {
throw new CheckErrorHandle(currFile.getAbsolutePath(), "File does not exist");
}
}
}

最佳答案

类似于:

Exception ex = null;
for (;;) {
ex = new Exception();
}
if (ex != null) throw ex;

或者,如评论所建议的那样:

List<Exception> errors = new ArrayList<>();
for (;;) {
errors.add(new Exception());
}
if (!errors.isEmpty()) {
//Do something with errors
}

一般的想法是您唯一可以做的事情 - 在抛出之前将异常存储在某个地方。如果您抛出异常 - 那么避免中断循环的唯一方法是立即捕获它。

关于java - 在不中断 java 循环的情况下抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35601428/

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