我希望剩余的代码即使在某些产品引发异常后也能继续。请在下面找到我的代码。
public class Example1 {
void productCheck(int[] weight) throws InvalidProductException {
for (int i = 0; i < weight.length; i++) {
System.out.println("Product -->"+weight[i]);
if (weight[i] < 100) {
System.out.println("Product exception-->"+weight[i]);
throw new InvalidProductException("Product Invalid");
}
}
}
public static void main(String args[]) {
Example1 obj = new Example1();
int[] weight = {110, 60, 10, 20, 100, 60 };
try {
obj.productCheck(weight);
} catch (InvalidProductException ex) {
System.out.println("Caught the exception for Product");
System.out.println(ex.getMessage());
}
}
}
public class InvalidProductException extends Exception
{
public InvalidProductException(String s)
{
// Call constructor of parent Exception
super(s);
}
}
输出:
Product -->110
Product -->60
Product exception-->60
Caught the exception for Product
Product Invalid
正如Andy所说,您的try-catch不在for循环的范围内,因此productCheck方法在抛出异常时退出,并继续向上堆栈,直到在主方法中捕获为止。如果您希望productCheck在抛出异常后继续for循环,则try-catch必须位于for循环内。请参见下文。
public class Example1 {
void productCheck(int[] weight) throws InvalidProductException {
for (int i = 0; i < weight.length; i++) {
try {
System.out.println("Product -->"+weight[i]);
if (weight[i] < 100) {
System.out.println("Product exception-->"+weight[i]);
throw new InvalidProductException("Product Invalid");
}
} catch (InvalidProductException ex) {
System.out.println("Caught the exception for Product");
System.out.println(ex.getMessage());
}
}
}
public static void main(String args[]) {
Example1 obj = new Example1();
int[] weight = {110, 60, 10, 20, 100, 60 };
obj.productCheck(weight);
}
}
public class InvalidProductException extends Exception
{
public InvalidProductException(String s)
{
// Call constructor of parent Exception
super(s);
}
}
如果在方法级别抛出异常,它无论如何都会终止。
一旦抛出异常,它将终止在那里的执行,并且异常将在主方法的try-catch块中捕获。
建议解决方案:
提取方法外的循环,将其放入另一个方法或主方法中,并在循环内添加try-catch块。
或
处理那里的错误本身,而不是抛出异常。
一旦发生异常,控件就会脱离for
循环。如果您希望循环继续,那么每个try-catch
都应该存在以处理每个weight
。否则,您可能会捕获所有错误的权重,然后抛出一个异常。您可以将代码重构为:
void productCheck(int[] weight) throws InvalidProductException {
List<Integer> errors = new ArrayList<>();
for (int i = 0; i < weight.length; i++) {
System.out.println("Product -->"+weight[i]);
if (weight[i] < 100) {
errors.add(Integer.valueOf(weight[i]));
}
}
if(!errors.isEmpty()){
System.out.println("Product exception for weights -->"+errors);
throw new InvalidProductException("Product Invalid");
}
}