java是否像重新引发相同的异常?
当我执行这段代码时,我得到了“最终”
public class Tester {
static void method() throws Exception {
throw new Exception();
}
public static void main(String... args) {
try {
method();
} catch (Throwable th) {
try {
new Exception();
} catch (Exception e) {
System.out.print("Exception");
} finally {
System.out.print("finally");
}
}
}
}
无法确定执行流程强>
# 1 楼答案
上述代码的输出将是
如果您想知道为什么输出不正确
那是因为在下面的代码行中
您只是声明了一个新的
Exception
对象,并不是真的抛出它如果希望输出为
Exception finally
,则必须通过放置throw new Exception();
而不是new Exception();
来抛出该对象然后,代码将如下所示:
输出
# 2 楼答案
如果代码
try
块中是否引发异常,则将执行finally
块