java - 异常处理无法访问的代码

标签 java exception-handling

以下是我的代码,当我评论 statement-2 时它符合罚款但当我取消评论时它给出编译时错误 “Unreachable Code”

我理解为什么在取消注释后出现错误,但我的问题是,即使我对其进行注释,bad() 仍然无法访问,因为我正在throw 异常是 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();
  }
}

最佳答案

but my question is even if i comment it still the bad() is unreachable as i am throwing an exception is catch then why it is not giving error for it ?

因为执行不需要进入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
}

关于java - 异常处理无法访问的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46145046/

相关文章:

java - Play Framework 无法读取数据库配置并注入(inject) JPAApi

java - JAX-RS 在自动 POJO 映射之前处理异常

java - SQLite 数据类型如何映射到 Java?

java - 旋转时 AsyncTask 中的 IllegalArgumentException

java - 累积验证违规的设计模式

java - 在 Java 中处理相同类型的不同异常?

oracle - 如何在异常处理 block 中重新引发pl/sql异常?

java - 链表返回值

haskell - 将错误适应于异常(exception)

c# - 在 C# 中处理所有异常的最简洁方法