Syntax aside, what is the difference between
try {
}
catch() {
}
finally {
x = 3;
}
and
try {
}
catch() {
}
x = 3;
Any code in the finally is ran in the even in the event of an unhandled exception. Typically the finally code is used to clean up local declarations of unmanaged code using .dispose().
In Java:
Finally always gets called, regardless of if the exception was correctly caught in catch(), or in fact if you have a catch at all.
There are several things that make a finally block useful:
These make finally blocks excellent for closing file handles or sockets.
In Java, you use it for anything that you want to execute regardless of whether you used a "return", just ran through the try block, or had an exception caught.
For example, closing a database session or a JMS connection, or deallocating some OS resource.
I am guessing it is similar in .NET?