以下是我的代码,当我评论 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/