Miljan Rakita Miljan Rakita - 7 months ago 18
Java Question

Finally sometimes confuse me

Today on college we talked a little bit about try - catch and finally.
I got confused about these two examples:

PrintWriter out = null;
try
{
out = new PrintWriter // We open file here
}catch(Exception e){
e.print... (whatever)
}finally{ /. And we close it here
out.close
}


What is difference if we closed file in finally or we just did it this way:

PrintWriter out = null;
try
{
out = new PrintWriter // We open file here
}catch(Exception e){
e.print... (whatever)
}
out.close;


This peace of code after catch will always execute.

Can you give me some good examples about difference when we use finally and when we put the code after catch.
I know that finally will always execute, but also program will always keep running after catch block

Answer

It would still make difference if the code throws Error. This is not caught within the code and therefore any part after try/catch/finally wouldn't be caught. If it's part of finally, it will be still executed even for Error.

Secondly, if for whatever reason e.printStackTrace() throw an exception (although it would be very rare), the same will happen - finally will be still executed.

In general finally is very safe way for releasing resources not matter what happens.

EDIT: Also note that your code is not really correct (no matter which version). If the PrintStream constructor throws an exception, the line out.close() will fail on NullPointerException.

Comments