I know finally
's purpose is to guarantee that some instructions or cleanup code get executed. But what is the actuall difference of using finally
or putting the code after the catch block.
I mean, give me an example of a case where you need to use finally
because otherwise the code might not execute at all.

- 16,104
- 25
- 61
- 88

- 15,672
- 28
- 94
- 206
-
A `finally` block executes even if you throw and not catch, or catch and rethrow, or `return`. `try{ throw new Error(); } finally { "do somehting"}` still runs the finally. – Benjamin Gruenbaum May 22 '14 at 20:40
-
could i get code example of each of those scenarios – Christopher Francisco May 22 '14 at 20:41
5 Answers
Finally will execute regardles of what happends in the catch block. Several cases exist.
catch(Exception E)
{
...
throw new OtherException(BetterMessage, E);
}
or
catch { return null; }
or
catch { SomeMethodThatWillThrowAnException(); }
Thus, even if you return or throw an exception to exit the Catch block, you'll still execute a finally block, while any code simply after the try-catch will be ignored.

- 10,458
- 1
- 28
- 40
-
1There's the `try { return; } ...` case too, as @Petros P suggested, and the `exit()` case. – Elist May 22 '14 at 20:54
finally executes no matter what.
One example
public void test() {
try {
int x = 0;
return;
} catch(Exception ex) {
ex.printStackTrace();
} finally {
System.out.println("Hello from finally");
}
System.out.println("Hello from after catch");
}
In this case "Hello from after catch" will not be printed but "Hello from finally" will.

- 6,682
- 9
- 45
- 73

- 99
- 8
A finally block is going to fire no matter what, even if you throw and catch. Code placed after the catch that's not in a finally block might not execute, for example if your catch might cause a process to end or an application to crash.

- 1,579
- 1
- 9
- 13
-
I see. If the application crashes, what kind of code would I be wanting to run? This is actually what i'm most interested in – Christopher Francisco May 22 '14 at 20:50
-
Make sure something gets logged somewhere about the crash. Try to alert another process about the failure. Save whatever user data you still can. Attempt to re-launch the application. Whatever you want to - this is more of an architecture decision; the FINALLY block is absolutely not *always* necessary, as there will certainly be times where it would have no use in context. – kyzen May 22 '14 at 20:55
The finally
block is executed regardless of whether or not an exception is thrown.
Your question is, what is the difference of using finally
, and putting code after the catch
block. If an exception is thrown, code after the catch
block won't be executed. If you place the code in the finally
block, it will.

- 16,477
- 11
- 74
- 110
There might occur some exception that you won't catch. finally
block guarantees execution of code inside of it even if unexpected exception is thrown.

- 376
- 1
- 8