Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there such case when in try\finally block the finally won't be executed?

I'm studying for my test in Object Oriented Programming and I was wondering if there is any case what so ever that considering the following code:

try {
    do something
} catch (someException e) {

} finally {
    do something
}

the finally block will not execute?

like image 283
Dave Avatar asked Aug 14 '10 17:08

Dave


People also ask

Is finally block executed after return in try block?

Yes, the finally block will be executed even after a return statement in a method. The finally block will always execute even an exception occurred or not in Java. If we call the System.

Will finally be executed after try?

Yes, finally will be called after the execution of the try or catch code blocks. The only times finally won't be called are: If you invoke System.

Does finally block get executed if either try or catch blocks are returning the control?

finally will be executed even if there is return in try and catch block. If return is replaced by System. exit(0) in try and catch block in above code and an exception occurs before it,for any reason.

Can finally block be executed without try block?

Yes, it is not mandatory to use catch block with finally.


2 Answers

Yes. If you crash the Java VM or otherwise muck things up via native code, cause the program to terminate, or loop/wait infinitely inside the try block.

Those are the only three cases which will avoid executing the finally block.

like image 69
Borealid Avatar answered Oct 12 '22 23:10

Borealid


If you call System.exit(0) in the try. Or make something that makes the JVM quit or hang (like a deadlock). Otherwise - no.

like image 30
Bozho Avatar answered Oct 12 '22 22:10

Bozho