What's the difference between
try {
fooBar();
} finally {
barFoo();
}
and
try {
fooBar();
} catch(Throwable throwable) {
barFoo(throwable); // Does something with throwable, logs it, or handles it.
}
I like the second version better because it gives me access to the Throwable. Is there any logical difference or a preferred convention between the two variations?
Also, is there a way to access the exception from the finally clause?
No Matter what The Finally block is always executed, So in General, Finally block is used, when you have sessions, Database connections or Files or sockets are open, then the code for closing those connections will be placed. This is just to make sure in an application no memory leaks or Any other issues should not occur.
These are two different things:
In your example you haven't shown the third possible construct:
And, like @codeca says in his comment, there is no way to access the exception inside the finally block, because the finally block is executed even if there is no exception.
Of course you could declare a variable that holds the exception outside of your block and assign a value inside the catch block. Afterwards you can access this variable inside your finally block.
These are not variations, they're fundamentally different things.
finally
is executed always,catch
only when an exception occurs.Generally when we use any resources like streams, connections etc.. we have to close them explicitly using finally block. In the program given below we are reading data from a file using FileReader and we are closing it using finally block.
Maybe other guys like me searched for something like this.
Information from this page tutpoint
In My reasearch Finally block is always executed and it is mainly "used for the any open connections to close" and to destroy something that is running unnecessarily.
Finally block is always executed. Catch block is executed only when an exception that matches the blocks parameter is catched.