在try finally块中从try块返回

4

我有两个代码片段,都在try和finally块中返回。第一个工作正常,在最后也打印出来,但是在标记为line1的行上编译时会出错。

第一段代码:

class abc {
public static void main(String args[]) {
    System.out.println("1");
    try {
        return;
    } catch (Exception ex) {
        System.out.println("Inside catch");
    } finally {
        System.out.println("2");
    }
    System.out.println("3");
}
}

第二个片段(编译时错误)

class Test11 {
public static void main(String[] args) {
    Test11 test = new Test11();
    System.out.println("1");
    try {
        return;
    } finally {
        System.out.println("2");
    }
    // COMPILER ERROR
    // System.out.println(test instanceof Test11);// line 1
}
}

回答: 第一段代码中,程序执行时会进入try块,如果在try块中出现异常,则跳转到catch块执行相应的代码,最后执行finally块中的语句。而第二段代码中没有这样的路径,因此finally块后面的语句将无法执行。

@santoshgore 编辑过了。在打字时离开了。 - Vishal
3
那么,你有什么问题? - JB Nizet
我认为这与return本身抛出Error有关。 - Boris the Spider
1
@JBNizet 为什么添加一个 catch 块会出现 "Unreachable statement" 错误 - 我想。 - Boris the Spider
使用此网站了解有关不可达代码的信息。(http://javaconceptoftheday.com/unreachable-code-dead-code-java) - santosh gore
显示剩余2条评论
1个回答

1

第一行是无法到达的语句。因为没有可能到达第一行。

如果异常抛出,它会在try内部中断。如果没有抛出异常,则从方法返回。

如果有catch块,它会确保如果try块中发生异常,它将转到第一行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接