Alex Rivera | Logout

What's the use of a finally block preceded by a catch-all catch block, in C#?

Asked 2010-01-11T12:04:54.043
11

Consider the following C# code structure (S0-S3 are placeholders for arbitrary code blocks):

try
{
    S0;
}
catch (Exception ex)
{
    S1;
}
finally
{
    S2;
}

S3;

In the case that S1 throws an exception inside the catch handler, S2 inside the finally will still execute (but S3 will not).

Question

Assuming that S1 cannot throw, is there any point in having S2 inside a finally block, rather than having it outside the try/catch/finally, just before S3?

Example

try
{
    // Do something that might throw
}
catch (Exception ex)
{
    // Save the exception to re-throw later
    // NB: This statement cannot throw an exception!
    this.cachedException = ex;
}
finally
{
    S2;
}

S3;

Is there any point in having the finally block? Would the following code not be equivalent (under the strict assumption that what's inside the catch block cannot throw):

try
{
    // Do something that might throw
}
catch (Exception ex)
{
    // Save the exception to re-throw later
    // NB: This statement cannot throw an exception!
    this.cachedException = ex;
}

// No finally block needed (?)
S2;
S3;

Secondary Question

Update: If it is accepted that the two code blocks above are equivalent (under the assumptions stated) then, taking into account the feedback on code clarity in the answers, would it be preferrable (and equivalent) to combine S2 and S3 inside the finally block?

try
{
    // Do something that might throw
}
catch (Exception ex)
{
    // Save the exception to re-throw later
    // NB: This statement cannot throw an exception!
    this.cachedException = ex;
}
finally
{
    S2; // Put S2 and S3 together inside the `finally` block to guard against
    S3; // future changes in the `catch` filter, or handling code.
}

                    
                    
                    
Edit
Report

2 Answers

3

Note that the finally clause is executed even if the try or catch block contains a return statement.

answered 2010-01-11T12:12:53.223
3

I think this is similar to putting brackets around if statement contents.

While you could argue that

if (x) y;

will not fail, whats to say that some less experienced programmer will not come along later and edit it to

if (x) y; z;

It may be the case that the finally block is not necessary for your code as it stands, but it is always a good idea to leave it in in case the code in the catch block ever changes.

if (x) 
{
    y;
}

always wins for me.

answered 2010-01-11T12:13:47.920

Your Answer