异常处理无法访问的代码

巴拉特布山:

以下是我的代码,当我注释statement-2时,它会被罚款,但是当我取消注释时,它会导致Compile Time Error "Unreachable Code"

我理解为什么在取消注释后会出现错误,但是我的问题是即使我注释它仍然bad()无法访问,因为我是throwing一个例外,那就是catch,那么为什么它没有给出错误呢?

class Varr 
{
  public static void main(String[] args) throws Exception
  { 
    System.out.println("Main");
    try {
      good();
    } catch (Exception e) {
      System.out.println("Main catch");
      //**Statement 1**    
      throw new RuntimeException("RE");
    } finally {
      System.out.println("Main Finally");
      //  **Statement 2**    
      throw new RuntimeException("RE2");
    }
    bad();
  }
}
大卫:

但是我的问题是,即使我发表评论,因为我抛出异常是catch,bad()仍然无法访问,那为什么它没有给出错误呢?

因为执行将不必要输入catch语句。
假设good()没有抛出的任何异常,这样你就不会在进入catch,因此bad(),然后执行:

public static void main(String[] args) throws Exception
{   
    System.out.println("Main");
    try {
        good(); // doesn't throw an exception
    } catch (Exception e) { 
        System.out.println("Main catch");
        throw new RuntimeException("RE");
    }
    bad(); // execution goes from good() to here
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章