13

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?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Dave
  • 141
  • 3

4 Answers4

17

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.

Borealid
  • 95,191
  • 9
  • 106
  • 122
  • 3
    Calling System.exit or turning of the computer probably counts as "cause the program to terminate" ... :-) – Rasmus Kaj Aug 14 '10 at 17:40
  • If in the try block, you return from the function containing this try/catch/finally phrase, would the finally block still execute ? – euphoria83 Aug 14 '10 at 22:31
  • 2
    @euphoria: yes, of course, that's part of the deal, that a `finally` block is guaranteed to execute when the code inside the corresponding `try` block exits under normal circumstances (including normal exceptions) – Jason S Aug 14 '10 at 22:40
  • Nitpicking: If a catch-block is executed before the finally, and endless loop/wait there will also prevent execution from reaching the finally block. Other than that, I think you got all cases :-) – meriton Aug 14 '10 at 22:41
5

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

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
2

The Java Language Specification guarantees that finally is invoked before the try-statement completes.

The try statement might not complete for the usual reasons, which have been enumerated in Borealid's answer.

meriton
  • 68,356
  • 14
  • 108
  • 175
0

The finally block will definitely get executed if the control comes out of the try or the catch block. If you some how manage to stop the control to come out of these blocks :

  • by writing exit statement, or

  • infinite loop etc.

then the finally block will not get executed. Generally we write the finally block for the "cleanup" purpose.

Shubham Pendharkar
  • 310
  • 1
  • 4
  • 17