【问题标题】:Return from try block in try finally block在 try finally 块中从 try 块返回
【发布时间】:2017-07-20 10:24:13
【问题描述】:

我有两个代码 sn-ps,我从 try 返回,也有 finally 块。第一个工作正常,也从 finally 打印,后来在标记为 line1 的行给出编译时错误。

第一个sn-p

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");
}
}

2nd sn-p(编译时错误)

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
}
}

回答: 原因是在第一个 sn-p 中有一条执行路径,然后是 catch 块,但在第二个 sn-p 中没有这样的路径,因此 finally 之后的语句无法访问。

【问题讨论】:

  • lass Test11 是你用代码写的。请检查语法。
  • @santoshgore 已编辑。打字时留下。
  • 那么,你的问题是什么?
  • 我认为这与return 本身抛出Error 会发生什么有关。
  • @JBNizet 为什么添加 catch 块会给出“无法访问的语句”错误 - 我认为。

标签: java try-catch try-catch-finally try-finally


【解决方案1】:

第 1 行是无法访问的语句。因为不可能去line1。

如果出现异常,它将在 try 中中断。如果不从方法返回。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 2015-09-05
    • 2010-10-01
    • 2012-05-18
    • 2015-12-06
    相关资源
    最近更新 更多