Re: Why finally?
- From: "Magnus" <no@xxxxxxxx>
- Date: Sun, 16 Apr 2006 10:24:16 +0200
"Jon Davis" <jon@xxxxxxxxxxxxxxxxxxxxxxxxxxxxx> skrev i melding
news:uuTSmZFYGHA.3972@xxxxxxxxxxxxxxxxxxxxxxx
I understand that the finally sub-block will execute regardless of whether
try succeeded or not. But so will code that follows try...catch. So then
what is the difference between ...
try {
do.something.that.breaks();
} catch {
do.something.that.works();
}
cleanup();
.. and ..
try {
do.something.that.breaks();
} catch {
do.something.that.works();
} finally {
cleanup();
}
.. other than organizational aesthetics ??
First of all, its not very common, or shouldn't be common to use catch all
statements.
The sole purpose of finally is to ensure that cleanup code is executed when
an exception is raised. Because of this it is also good code practise, c#
coders know that any cleanup will be within the finally block.
Using a finally block will also do a much better job than relying on catch
all statements and a subsequent line of code that in most cases will be
fired, but not all.
For example, consider the following cases:
- An exception is raised in the catch block, finally will be executed, your
first example will not.
- Some time in the future, the code is modified so that the catch statement
only catches specific exceptions, finally will be executed, your first
example will not.
- Some time in the future, your catch statement includes a return statement,
finally will be executed, your first example will not.
- Im sure there is more..
So no, its not just aesthetics, finally is for cleanup, your example just
happen to work in your idea of how the intended code will be executed, and
assumptions such as yours will cause you pain in the end.
- Magnus
.
- References:
- Why finally?
- From: Jon Davis
- Why finally?
- Prev by Date: Re: Why finally?
- Next by Date: Some clarification needed C# vs. Javascript
- Previous by thread: Re: Why finally?
- Next by thread: Adding my menu to Context Menu of IE
- Index(es):
Relevant Pages
|