下面是一个传播异常处理机制的类问题,所需的输出是异常。任何人都可以解释为什么输出是异常,在此先感谢。
Class Question {
public void m1() throws Exception {
thử {
m2();
} finally {
m3();
}
}
public void m2() throws RuntimeException {
throw new RuntimeException();
}
public void m3() throws Exception {
throw new Exception();
}
public static void main(String[] args) throws Exception {
Question q = new Question();
thử {
q.m1();
} catch (RuntimeException re) {
System.out.println("RuntimeException");
} catch (Exception e) {
System.out.println("Exception");
}
}
在Exception Handeling中,finally block 将被强制执行,无论try block 中是否发生天气错误,
这里 m1()
在 try block 中调用 m2()
,而 m2()
抛出 RuntimeException
控制返回到 m1()
并带有 RuntimeException
但 finally block 将在从 try 或 catch block 返回控件之前强制执行。 ,这就是为什么 m3()
被 finally Block 调用并且 m3()
抛出 Ngoại lệ
,这里是对 finally block Exception< 的响应
phụ thuộc vào m3()
抛出将由 m1()
抛出。这就是为什么您会得到 Ngoại lệ
Và catch(Exception e)
block 将要执行的原因。
finally block 强制执行。如下例:
class Question {
public void m1() throws Exception {
thử {
// control forworded to finally block(if Available) before returning from try or catch block.
trở lại;
} finally {
m3();
}
}
public void m3() throws Exception {
throw new Exception();
}
public static void main(String[] args) throws Exception {
Question q = new Question();
thử {
q.m1();
} catch (RuntimeException re) {
System.out.println("RuntimeException");
} catch (Exception e) {
System.out.println("Exception");
}
}
我希望它能帮助你理解异常处理,也能帮助你解决 future 的问题。
Tôi là một lập trình viên xuất sắc, rất giỏi!