finally
块主要用于防止可以在资源类的close()
方法中实现的资源泄漏。使用带有try-with-resources
语句的finally块是什么,例如:
class MultipleResources {
class Lamb implements AutoCloseable {
public void close() throws Exception {
System.out.print("l");
}
}
class Goat implements AutoCloseable {
public void close() throws Exception {
System.out.print("g");
}
}
public static void main(String[] args) throws Exception {
new MultipleResources().run();
}
public void run() throws Exception {
try (Lamb l = new Lamb(); Goat g = new Goat();) {
System.out.print("2");
} finally {
System.out.print("f");
}
}
}
参考:K.Seirra,B。Bates OCPJP Book
答案 0 :(得分:3)
就像在常规try-catch-finally
块中一样 - 当你想要总是发生某些事情时,使用finally
块,无论try
块中的操作是否成功。
我认为你的问题是提供一些真正有用的用例。尝试想象一种情况,当你必须告诉一个协作者(或发布一个事件)你的处理完成 - 无论结果如何。然后,您可以在finally
块中输入可用于宣布完成处理的代码。
请注意,当try-with-resources
块中没有catch
的某些操作引发异常时,该块之后的代码将不会被执行。
答案 1 :(得分:1)
答案 2 :(得分:0)
这个程序可能会向您展示Java中finally关键字的工作以及finally关键字
的重要性class Example {
public static void main(String args[]) {
int i = 1, j = 0;
try {
System.out.println("The result is " + i / j);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("This is statement would never executed");
System.out.println("Because catch() block is not catching exception from try");
}
finally {
// finally block will always execute
System.out.println("This statement will always executed");
System.out.println("Becuase this is finally");
}
// These 3 statements would never executed
// They will execute if catch block catches the Exception from try
System.out.println("This is statement would never executed");
System.out.println("Because catch() block is not catching exception from try");
System.out.print(" and program is interrupted after finally");
}
}