gpt4 book ai didi

java - 核心-java异常处理

转载 作者:行者123 更新时间:2023-11-29 04:32:42 27 4
gpt4 key购买 nike

下面是一个传播异常处理机制的类问题,所需的输出是异常。任何人都可以解释为什么输出是异常,在此先感谢。

 Class Question {

public void m1() throws Exception {

try {

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();

try {

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() 抛出 Exception ,这里是对 finally block Exception< 的响应m3() 抛出将由 m1() 抛出。这就是为什么您会得到 Exception 并且 catch(Exception e) block 将要执行的原因。

finally block 强制执行。如下例:

class Question {

public void m1() throws Exception {

try {


// control forworded to finally block(if Available) before returning from try or catch block.
return;

} finally {

m3();

}
}

public void m3() throws Exception {

throw new Exception();

}
public static void main(String[] args) throws Exception {

Question q = new Question();

try {

q.m1();

} catch (RuntimeException re) {

System.out.println("RuntimeException");

} catch (Exception e) {

System.out.println("Exception");
}
}

我希望它能帮助你理解异常处理,也能帮助你解决 future 的问题。

关于java - 核心-java异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43167605/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com