没有抛出条款

时间:2011-05-11 08:18:51

标签: java exception

这个程序是正确的,并且编译和运行。但为什么方法'a'没有抛出声明?

class Exception1 {
      public void a() 
        {
            int array[] = new int[5];
            try
            {
                System.out.println("Try");
                array[10]=1;
            }
            catch (Exception e)
            {
               System.out.println("Exception");

                throw e;
            }
            finally
            {
                System.out.println("Finally");
                return;
            }
        }
    public static void main(String[] args) 
        {
            Exception1 e1 = new Exception1();

            try {
                e1.a();
            } 
            catch(ArrayIndexOutOfBoundsException e)
            {
                System.out.println("Catch");
            }
            System.out.println("End of main");
        }
}

2 个答案:

答案 0 :(得分:4)

问题是return块中的finally

由于finally始终执行,并且始终突然完成(使用未经检查的例外或使用return), throw e - 块中的catch(或try块中任何未经检查的异常)无法在调用堆栈上向下传播。

如果删除return,那么您会注意到编译器不会接受该代码,并声明Exception未声明在方法a()上抛出。< / p>

答案 1 :(得分:2)

ArrayIndexOutOfBoundsException是未经检查的异常,这意味着既不需要声明也不需要明确捕获。

所以说得简单。在java中,您已经检查并取消选中了异常(和错误,现在让它们保留)。检查一个扩展Exception,如果代码可能抛出它们,则必须在抛出和处理时声明。

另一方面,未经检查的异常扩展RuntimeException并且没有必要声明它们并且您不需要处理它们。以NullPointerException为例。如果你需要处理它们,你将需要很多尝试捕获,因为NPE几乎可以在任何代码行上发生。