0

If the statements after the catch block is going to be executed anyway what is the real use of finally block in java? Example

 try {
 //Code
}
catch (Exception e)
{
//Code
}
finally {
 System.out.println("anyway it will be        executed");
 }

System.out.println("anyway it will be executed");
Manu Jo Varghese
  • 360
  • 1
  • 14
  • Anywhere in the code there may be a return statement. Even though the code may have returned to the calling method, the code in the `finally` block will **still** be executed – Scary Wombat Aug 02 '18 at 04:20

2 Answers2

6

The statement at the bottom is not guaranteed to be executed. For example, if

  • the try block or a matched catch block use return (or break in some circumstances)
  • none of the catch blocks match the exception, and the exception is thus uncaught
  • another (or same) exception is raised (and not caught) inside catch

In all of these cases, finally statements are guaranteed to be executed.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • and even if we add `System.exit(0)` in try block – Ashish Kudale Aug 02 '18 at 04:28
  • @AshishKudale: I haven't tried, but not according to [Does finally always execute in Java?](https://stackoverflow.com/questions/65035/does-finally-always-execute-in-java). In Python, `finally` is executed even on `exit`, but Java doesn't seem to offer the same courtesy. – Amadan Aug 02 '18 at 04:29
  • Adding to the answer. The primary use of finally is to release resources that were locked inside the try block. For example: Suppose you have a file opened in try. You can write several catch blocks handling multiple exception types. And its not wise to close the opened file in each catch block(Redundancy). And so Finally helps you here by having the close file logic written only in one place. – jeffry copps Aug 02 '18 at 04:30
  • @AshishKudale No finally block will not be executed after System.exit(0) and your program will be terminated immediately after executing System.exit(0).. – DhaRmvEEr siNgh Aug 02 '18 at 05:22
  • 1
    @DhaRmvEErsiNgh: Getting further off-topic now, but no, not _quite_ immediately - there's still (barely) time for shutdown hooks (see [`Runtime.addShutdownHook`](https://docs.oracle.com/javase/10/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)) ). – Amadan Aug 02 '18 at 05:27
  • Thanks @Amadan. I was not aware of that :) – DhaRmvEEr siNgh Aug 02 '18 at 05:31
1

Your catch can return or throw an exception, and before that happens you can use finally to release resources for example. Finally executes before the control is passed back to the caller.

Coder-Man
  • 2,391
  • 3
  • 11
  • 19