加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

c# – 我可以执行多个与一个try块对应的catch块吗?

发布时间:2020-12-14 19:22:24 所属栏目:Java 来源:网络整理
导读:考虑我有一个包含3个语句的try块,所有这些语句都会导致异常.我希望所有3个例外都由它们相关的catch块处理..是否可能? 像这样的东西 > class multicatch{ public static void main(String[] args) { int[] c={1}; String s="this is a false integer"; try {

考虑我有一个包含3个语句的try块,所有这些语句都会导致异常.我希望所有3个例外都由它们相关的catch块处理..是否可能?

像这样的东西 – >

class multicatch
{
    public static void main(String[] args)
    {
        int[] c={1};
        String s="this is a false integer";
        try
        {
            int x=5/args.length;
            c[10]=12;
            int y=Integer.parseInt(s);
        }
        catch(ArithmeticException ae)
        {
            System.out.println("Cannot divide a number by zero.");
        }
        catch(ArrayIndexOutOfBoundsException abe)
        {
            System.out.println("This array index is not accessible.");
        }
        catch(NumberFormatException nfe)
        {
            System.out.println("Cannot parse a non-integer string.");
        }
    }
}

是否有可能获得以下输出? – >>

Cannot divide a number by zero.
This array index is not accessible.
Cannot parse a non-integer string.
最佳答案

Is it possible to obtain the following output?

不,因为只会抛出一个异常.一旦抛出异常,执行就会离开try块,并且假设有一个匹配的catch块,它会继续存在.它不会返回到try块,因此您无法获得第二个异常.

有关异常处理的一般课程,请参阅Java tutorial;有关详细信息,请参阅section 11.3 of the JLS.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读