When to use What - try / catch / finally in Java

The finally block is used to ensure resources are recovered regardless of any problems that may occur.

There are several variations for using the finally block, according to how exceptions are handled. (See the excellent book The Java Programming Language by Arnold, Gosling, and Holmes for related information.)

Situation 1

If a method throws all exceptions, then it may use a finally with no catch 

Situation 2

If a method handles all exceptions, then an interesting variation is to nest a try..finally within a try..catch. This style is particularly useful when the finally block throws the same exceptions as the rest of the code (which is common with java.io operations.) Although this style may seem slightly complex, it appears to be superior to alternative style 

Situation 3
A more verbose style places a catch within the finally. This style is likely the least desirable, since it has the most blocks

0 comments: