在前一个catch块中处理的重新启动异常 [英] rethrowing exception handled in preceding catch block

查看:222
本文介绍了在前一个catch块中处理的重新启动异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>)


详细来说,在Java SE 7及更高版本中,当您在catch子句中声明一个或多个
异常类型,并重新抛出由此catch块处理的
异常,编译器验证重新抛出异常的类型符合以下条件:



- try块能够抛出它。



- 没有其他可以处理的catch块。



- 它是一个catch子句的异常参数的子类型或超类型。


请注意第二点(



研究以下代码:

  static private void foo()throws FileNotFoundException {
try {
throw new FileNotFoundException();
} catch(FileNotFoundException e){
e.printStackTrace();
} catch(IOException e){
throw e;
}
}

此代码编译好。根据我的意见,在阅读上述文章的引用之后,我期望看到编译器将验证它,我会得到编译器错误。



我明白第二点错了吗? >

解决方案

这是非常好的,因为 FileNotFoundException 是从 IOException ,并且因为您从不太具体到更具体的内容,不应该有任何问题。






编辑:

  static private void foo()throws FileNotFoundException {
try {
throw新的FileNotFoundException();
} catch(IOException e){
e.printStackTrace();
} catch(FileNotFoundException e){
throw e;
}
}


on oracle ofiicial site write (http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html#rethrow)

In detail, in Java SE 7 and later, when you declare one or more exception types in a catch clause, and rethrow the exception handled by this catch block, the compiler verifies that the type of the rethrown exception meets the following conditions:

-The try block is able to throw it.

-There are no other preceding catch blocks that can handle it.

-It is a subtype or supertype of one of the catch clause's exception parameters.

Please concentrate on second point (There are no other preceding catch blocks that can handle it. )

Research following code:

static private void foo() throws FileNotFoundException  {
        try {
            throw new FileNotFoundException();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw e;
        }
    }

This code compiles good. According my opinion after reading quote from mentioned article I expect to see that compiler will verify it and I will get compiler error.

Did I understand second point wrong?

解决方案

This is perfectly fine because the FileNotFoundException is derived from IOException, and because you go from less specific to a more specific there should not be any issues.


edit:

static private void foo() throws FileNotFoundException  {
    try {
        throw new FileNotFoundException();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        throw e;
    }
}

这篇关于在前一个catch块中处理的重新启动异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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