Syntax aside, what is the difference between
try {
}
catch() {
}
finally {
x = 3;
}
and
try {
}
catch() {
}
x = 3;
The finally block will always be called (well not really always ... ) even if an exception is thrown or a return statement is reached (although that may be language dependent). It's a way to clean up that you know will always be called.
@iAn and @mats:
I would not "tear down" anything in finally {} that was "set up" within the try {} as a rule. Would be better to pull the stream creation outside of the try {}. If you need to handle an exception on stream create this could be done in a greater scope.
StreamReader stream = new StreamReader("foo.bar");
try {
mySendSomethingToStream(stream);
}
catch(noSomethingToSendException e) {
//Swallow this
logger.error(e.getMessage());
}
catch(anotherTypeOfException e) {
//More serious, throw this one back
throw(e);
}
finally {
stream.close();
}
Well, for one thing, if you RETURN inside your try block, the finally will still run, but code listed below the try-catch-finally block will not.
So you can clean up any open connections, etc. initialized in the try block. If you opened a connection and then an exception occurred, that exception would not be properly closed. This type of scenario is what the finally block is for.
@Ed, you might be thinking of something like a catch(...)
that catches a non-specified exception in C++.
But finally
is code that will get executed no matter what happens in the catch
blocks.
Microsoft has a help page on try-finally for C#
try catch finally is pretty important construct. You can be sure that even if an exception is thrown, the code in finally block will be executed. It's very important in handling external resources to release them. Garbage collection won't do that for you. In finally part you shouldn't have return statements or throw exceptions. It's possible to do that, but it's a bad practice and can lead to unpredictable results.
If you try this example:
try {
return 0;
} finally {
return 2;
}
The result will be 2:)
Comparison to other languages: Return From Finally