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

6 java arrays exception-handling exception

我的示例代码如下:

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");
        }            
    }
}
Run Code Online (Sandbox Code Playgroud)

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

San*_*air 8

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


Jav*_*ava 6

您的代码应如下所示:

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");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)