Alex Rivera | Logout

What is the point of the finally block?

Asked 2008-09-08T20:41:49.307
35

Syntax aside, what is the difference between

try {
}
catch() {
}
finally {
    x = 3;
}

and

try {
}
catch() {
}

x = 3;

edit: in .NET 2.0?


so

try {
    throw something maybe
    x = 3
}
catch (...) {
    x = 3
}

is behaviourally equivalent?

Edit
Report

2 Answers

45

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.

answered 2008-09-08T20:43:44.000
6

There are several things that make a finally block useful:

  1. If you return from the try or catch blocks, the finally block is still executed, right before control is given back to the calling function
  2. If an exception occurs within the catch block, or an uncaught type of exception occurs in the try block, the code in the finally block is still executed.

These make finally blocks excellent for closing file handles or sockets.

answered 2008-09-08T21:11:15.367

Your Answer