以下是我的代码,当我评论 statements-2 时,它符合罚款要求,但当我取消注释时,它会给出 Compile Time Error "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();
}
}
Run Code Online (Sandbox Code Playgroud)
但我的问题是,即使我评论它, bad() 仍然无法访问,因为我抛出异常是 catch 那么为什么它没有给出错误?
因为执行时就不需要在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
}
Run Code Online (Sandbox Code Playgroud)