Java Reference
In-Depth Information
try {
// Code for try block goes here
}
finally {
// Code for finally block goes here
}
When you use a try-catch-finally block, your intention is to execute the following logic:
Try executing the code in the try . If the code in the try block throws any exception, execute the
matching catch block. Finally, execute the code in the finally block no matter how the code in the
try and catch blocks finish executing.
When you use a try-finally block, your intention is to execute the following logic:
Try executing the code in the try block. When the code in the try block finishes, execute the code in
the finally block.
a finally block is guaranteed to be executed no matter what happens in the associated try and/or catch
block. there are two exceptions to this rule: the finally block may not be executed if the thread that is executing the
try or catch block dies, or a Java application may exit, for example, by calling System.exit() method, while executing
the try or catch block.
Tip
Why do you need to use a finally block? Sometimes you want to execute two sets of statements, say set-1
and set-2 . The condition is that set-2 should be executed no matter how the statements in set-1 finish executing.
For example, statements in set-1 may throw an exception or may finish normally. You may be able to write the
logic, which will execute set-2 after set-1 is executed, without using a finally block. However, the code may not
look clean. You may end up repeating the same code multiple places and writing spaghetti if-else statements. For
example, set-1 may use constructs, which make the control jump from one point of the program to another. It may
use constructs like break , continue , return , throw , etc. If set-1 has many points of exit, you will need to repeat the
call to set-2 before exiting at many places. It is difficult and ugly to write logic that will execute set-1 and set-2 . The
finally block makes it easy to write this logic. All you need to do is to place set-1 code in a try block and the set-2
code in a finally block. Optionally, you can also use catch blocks to handle exceptions that may be thrown from
set-1 . You can write Java code to execute set-1 and set-2 as follows:
try {
// Execute all statements in set-1
}
catch(MyException e1) {
// Handle any exceptions here that may be thrown by set-1
}
finally {
// Execute statements in set-2
}
If you structure your code to execute set-1 and set-2 as shown above, you get cleaner code with guaranteed
execution of set-2 after set-1 is executed.
 
 
Search WWH ::




Custom Search