Will a subclass catch block catch a checked parent exception?

被刻印的时光 ゝ 提交于 2019-12-10 03:22:36

问题


I have a method with a checked exception for a parent class, which can throw exceptions of the type parent and subclass

public void method() throws ParentException {
    if( false ) throw new ParentException();
    else if( true ) throw new ChildException(); // this one is thrown
}

and I have a cascade catch block, which first has the child exception

try {
    method();
} catch (ChildException e) {
    // I get here?
} catch (ParentException e) {
    // or here?

}

Which block will catch the exception thrown? Since the method declares explicitly the ParentException only, would the ChildException be shown as an instance of ParentException?


回答1:


The catch block will always catch the most specific exception available to it, working its way up from the inheritance hierarchy.

I should stress that your catch blocks must be in the inheritance hierarchy order; that is to say, you may not declare a catch block with ParentException followed by ChildException, as that is a compilation error. What you have there (in terms of catch blocks) is valid.

A more common use case of this is when handling file IO; you can first catch FileNotFoundException, then IOException, should the error be less specific than FileNotFoundException.



来源:https://stackoverflow.com/questions/38442108/will-a-subclass-catch-block-catch-a-checked-parent-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!