Answer the question
In order to leave comments, you need to log in
Is the finally block always executed?
Bruce Eckel in "Java Philosophy" writes on page 388 that
the finally block is always executed
if the construction fails, the finally block is not executed
//: exceptions/Cleanup.java
// Гарантированное освобождение ресурса
public class Cleanup {
public static void main(String[] args) {
try {
lnputFile in = new InputFile("Cleanup.java")j
try {
String s;
int i = 1;
while((s = in.getLine()) != null)
; // Обработка данных по строкам...
} catch(Exception e) {
System.0ut.println("Перехвачено исключение Exception в main");
e .printStackTrace(System.out);
} finally {
in.dispose();
}
} catch(Exception e) {
System.out.println("Ошибка при конструировании InputFile");
}
}
} /* Output:
dispose() успешен
*///:~
Take a closer look at the logic behind what's going on: the lnputFile object is actually
constructed in its own try block. If a construction error occurs
, the program enters the outer catch block and the dispose() method is not called. But if
the construction succeeds, you need to make sure that the object is finished with, so a new try block is created
immediately after the construction .
The finally block that performs the final actions is linked to the inner try block; if the construction fails, the finally block is not executed , but it will always be executed if the construction succeeds
Answer the question
In order to leave comments, you need to log in
The author writes correctly. If an exception is thrown on the line lnputFile in = new InputFile("Cleanup.java")j , then it will immediately fall into catch(Exception e) { System.out.println("Error constructing InputFile"); } . Here, the finally is not executed, since the execution of the code does not enter the try block to which that finally is attached.
But if an exception is thrown somewhere inside the while((s = in.getLine()) != null) loop , then the inner catch block and finally block will fire. The outer catch will not be executed.
What if you execute System.exit() in a try or catch block?
finally is always executed
Why questions? I haven’t seen Java in my eyes, but it’s a matter of minutes to check
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question