繁体   English   中英

异常处理无法访问的代码

[英]Exception Handling Unreachable code

以下是我的代码,当我评论语句-2然后它符合罚款,但当我取消注释它给出编译时错误"Unreachable Code"

我理解为什么我在取消注释后会出现错误,但我的问题是,即使我评论它仍然是bad()无法访问,因为我throwing异常是捕获然后为什么它没有给它错误?

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语句。
假设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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM