异常处理无法访问的代码
Exception Handling Unreachable code
以下是我的代码,当我评论 statement-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();
}
}
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
}
以下是我的代码,当我评论 statement-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();
}
}
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
}