gpt4 book ai didi

java - try-catch-finally 和其余的方法执行顺序

转载 作者:行者123 更新时间:2023-12-03 23:14:18 26 4
gpt4 key购买 nike

我对使用 try/catch/finally 子句有疑问,让我解释一下:我知道每个在其声明中声明异常规范的方法都必须(在调用方法中)用一个 try block 包围,然后是一个可以捕获该异常的 catch block (除非我不声明调用方法抛出也异常(exception))。如果调用方法在 try-catch 之后还有其他语句,则无论发生什么情况(是否抛出异常)都会执行这些语句。所以如果我有以下代码:

 public class ExceptionCall {
Throwing t = new Throwing();
public void methodTry(){
while(true){
try {
if (t.flag++==0)
t.throwing();
System.out.println("no exception");
}
catch (MyException e) {
e.printStackTrace(System.err);
System.out.println("working on it!");
}
finally{
System.out.println("finally clause");
}
System.out.println("out");
if (t.flag==2)
break;
}
}
}

这里 Throwing 有一个名为(猜猜是什么 :) )throwing() 的方法,它被声明为抛出一个 MyException 异常,并且有一个名为 flag 的公共(public)字段,其中包含一个int 初始化为 0 以提供一种条件检查。

因此有几次无论 try block 中发生什么, protected 区域之外的代码都会执行。

所以我的问题是,finally block 是做什么用的?我的意思是,我知道当调用方法从 try 或 catch block 返回时它会派上用场(在这种情况下我可以在 catch 中有一个 break 语句并且 finally 将被执行),但在这种情况下是什么区别??

最佳答案

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

参见:https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

关于java - try-catch-finally 和其余的方法执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29416982/

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