Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you really need the 'finally' block

There are 3 permutations of a try...catch...finally block in java.

  1. try...catch
  2. try...catch...finally
  3. try...finally

Once the finally block is executed, control goes to the next line after the finally block. If I remove the finally block and move all its statements to the line after the try...catch block, would that have the same effect as having them in the finally block?

like image 639
Amit Kumar Gupta Avatar asked Oct 05 '10 07:10

Amit Kumar Gupta


People also ask

Is a Finally block required after a catch block?

Finally block is optional, as we have seen in previous tutorials that a try-catch block is sufficient for exception handling, however if you place a finally block then it will always run after the execution of try block. 3.

Is finally necessary java?

Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the necessary statements that need to be printed regardless of the exception occurs or not. The finally block follows the try-catch block.

What is the point of finally in try-catch?

The purpose of a finally block is to ensure that code gets run in three circumstances which would not very cleanly be handled using "catch" blocks alone: If code within the try block exits via return.


1 Answers

I know this is a very old question but I came across today and I was confused by the answers given. I mean, they are all correct but all answer on a theoretical or even philosophical level when there is a very straightforward practical answer to this question.

If you put a return, break, continue or any other java keyword that changes the sequential execution of code inside the catch block (or even try block), the statements inside the finally block will still be executed.

For example:

public void myFunc() {      double p = 1.0D;     String str = "bla";     try{         p = Double.valueOf(str);     }     catch(Exception ex){         System.out.println("Exception Happened");         return;  //return statement here!!!     }finally{         System.out.println("Finally");     }     System.out.println("After finally"); } 

when executed this code will print:

Exception Happened  Finally 

That is the most important reason for the existence of a finally block. Most answers imply it or refer to it on the sidelines but none of them is putting emphasis on it. I think because this is kind of a newbie question such a straightforward answer is very important.

like image 55
Angelos Makrygiorgos Avatar answered Oct 11 '22 02:10

Angelos Makrygiorgos