Java Reference
In-Depth Information
pre();
try {
// other actions
} finally {
post();
}
If pre succeeds then we enter the try block and no matter what occurs
we are guaranteed that post gets executed. Conversely, if pre itself fails
for some reason and throws an exception, then post does not get ex-
ecutedit is important that pre occur outside the try block in this situation
because post must not execute if pre fails.
You saw the second form of the idiom in the stream searching example.
In that case pre returns a value that can be used to determine whether
or not it completed successfully. Only if pre completed successfully is
post invoked in the finally clause:
Object val = null;
try {
val = pre();
// other actions
} finally {
if (val != null)
post();
}
In this case, we could still invoke pre outside the try block, and then we
would not need the if statement in the finally clause. The advantage
of placing pre inside the try block comes when we want to catch both
the exceptions that may be thrown by pre and those that may be thrown
by the other actionswith pre inside the TRy block we can have one set of
catch blocks, but if pre were outside the TRy block we would need to use
an outer TRy-catch block to catch the exceptions from pre . Having nested
 
Search WWH ::




Custom Search