2

if i have a following code

      try{

           //some code

      }catch(Exception e){

           //some code

      }finally{

      }

what happens to the finally block in the following cases

  1. if any checked exceptions happen.

  2. if System.exit() is called.

  3. if any unchecked exceptions happen.

  4. if any errors happen.

GuruKulki
  • 25,776
  • 50
  • 140
  • 201

7 Answers7

9
  1. finally block is executed.

  2. finally block is not executed unless System.exit() throws an Exception, in which case the finally block is executed. (see How does Java's System.exit() work with try/catch/finally blocks?)

  3. finally block is executed.

  4. finally block is executed (depends on the type of error though, if you're talking about a JVM error, then there's really no telling what might happen).

Community
  • 1
  • 1
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
3

JLS 14.20.2 Execution of try-catch-finally

Everything's spelled out pretty clearly. finally will always be executed in all of those cases, with the obvious exception of a successful System.exit.

System.exit(int status)

Terminates the currently running Java Virtual Machine [...] This method never returns normally.

polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
2
  1. Finally will be executed.
  2. Finally won't be executed, unless System.Exit() throws an exception.
  3. Finally will be executed.
  4. Finally will be executed.
Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
1
  • 1 and 3 - The catch clause will be triggered, and after that - the finally clause
  • 4 - only the finally clause will be triggered
  • 3 - the program will exit and finally won't be executed. It's because "This method never returns normally. " The finally will be triggered in case System.exit(0) throws an exception (SecurityException)
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
0

Assuming that none of the 4 items happens in the finally block, then the finally block will be executed before the code exits unless the VM crashes, then all bets are off. EDIT System.exit() actually bypasses finally {}.

Chuk Lee
  • 3,570
  • 22
  • 19
0

The only way to escape a finally clause is System.exit. Every other case the finally block is reached.

http://www.javaworld.com/javaworld/jw-02-1997/jw-02-hood.htm

http://java.sun.com/docs/books/jls/second_edition/html/exceptions.doc.html (section 11.3)

are good reads about this.

Kannan Ekanath
  • 16,759
  • 22
  • 75
  • 101
0

1.if any checked exceptions happen. code flows as

a. try...
b. [checked exception]
c. skip the rest of try and execute catch block for the checked exception
d. execute finally

2.if System.exit() is called.
finally is executed. 3.if any unchecked exceptions happen.
a. try...
b. [unchecked exception]
c. skip the rest of try and move to finally
d. execute finally

4.if any errors happen.
a.finally is executed.But the program is toast before JVM throws an "Error"

frictionlesspulley
  • 11,070
  • 14
  • 66
  • 115