抛出exception后如何继续执行java程序?

我的示例代码如下:

public class ExceptionsDemo { public static void main(String[] args) { try { int arr[]={1,2,3,4,5,6,7,8,9,10}; for(int i=arr.length;i<10;i++){ if(i%2==0){ System.out.println("i =" + i); throw new Exception(); } } } catch (Exception e) { System.err.println("An exception was thrown"); } } } 

我的要求是,在捕获exception后,我想处理数组的其余元素。 我怎样才能做到这一点?

您的代码应如下所示:

 public class ExceptionsDemo { public static void main(String[] args) { for (int i=args.length;i<10;i++){ try { if(i%2==0){ System.out.println("i =" + i); throw new Exception(); // stuff that might throw } } catch (Exception e) { System.err.println("An exception was thrown"); } } } } 

在for循环中移动try catch块然后它应该工作

你需要稍微重新构造它,以便try / catch在for循环中,而不是封闭它,例如

 for (...) { try { // stuff that might throw } catch (...) { // handle exception } } 

顺便说一句,你应该避免像流程控制一样使用exception – exception应该用于特殊事情。

只是不要抛出exception,然后:

 int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int i = 0; i < arr.length; i++) { if (i % 2 == 0) { System.out.println("i = " + i); } } 

或抛出它,并在循环中捕获它,而不是在外面(但我没有看到在这个简单的例子中抛出exception的重点):

 int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int i = 0; i < arr.length; i++) { try { if (i % 2 == 0) { System.out.println("i = " + i); throw new Exception(); } } catch (Exception e) { System.err.println("An exception was thrown"); } } 

旁注:看看代码在正确缩进时如何更容易阅读,并在运算符周围包含空格。

您不能这样做,因为您的数组是在try子句中定义的。 如果您希望能够访问它,请将其移出。 也许你应该以某种方式存储我在exception中导致exception,以便你可以继续它。