如何继续执行Java程序抛出异常后? [英] How to continue executing a java program after an Exception is thrown?

查看:214
本文介绍了如何继续执行Java程序抛出异常后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的示例code是如下:

My sample code is as follows:

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");
        }            
    }
}

我的要求是,在异常被捕获后,我要处理的阵列的剩余的元素。我怎样才能做到这一点?

My requirement is that, after the exception is caught I want to process the remaining elements of the array. How can I do this?

推荐答案

您code应该如下:

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");
            }
        }
    }
}

这篇关于如何继续执行Java程序抛出异常后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆