Syntax aside, what is the difference between
try {
}
catch() {
}
finally {
x = 3;
}
and
try {
}
catch() {
}
x = 3;
>
The finally block is in the same scope as the try/catch, so you will have access to all the variables defined inside.
Imagine you have a file handler, this is the difference in how it would be written.
try
{
StreamReader stream = new StreamReader("foo.bar");
stream.write("foo");
}
catch(Exception e) { } // ignore for now
finally
{
stream.close();
}
compared to
StreamReader stream = null;
try
{
stream = new StreamReader("foo.bar");
stream.write("foo");
} catch(Exception e) {} // ignore
if (stream != null)
stream.close();
Remember though that anything inside finally isn't guaranteed to run. Imagine that you get an abort signal, windows crashes or the power is gone. Relying on finally for business critical code is bad.