ChrisM
ChrisM

Reputation: 167

Can two or more 'try/catch' statements share a 'finally' statement in C#?

Can two or more 'try/catch' statements share a 'finally' statement in C#? I am trying to follow a coworker's code and it's very sloppy and unexecutable.

Example:

try
{
    Function1()
}
catch { }
try
{
    Function2();
}
catch { }
try
{
    Function3();
}
catch { }
finally
{
    EndFunction();
}

Upvotes: 1

Views: 391

Answers (5)

Kirk Woll
Kirk Woll

Reputation: 77596

No, each try/catch/finally sequence is a discrete block-level statement. However, each try can have zero, one or more catch clauses followed by an optional finally clause.

Looking at the code, I see no compelling reason it isn't written as:

try
{
    Function1()
    Function2();
    Function3();
}
finally
{
    EndFunction();
}

As Jordão mentions, empty (uncommented) catch handlers are a terrible practice. And there's no reason for splitting out the various function calls into separate try blocks if you want them all handled by the same finally block.

Upvotes: 6

Jason
Jason

Reputation: 15931

if you are expecting specific exception from each call you can chain your catch statements

try
{
 Function1();
 Function2();
 Function3();
} catch(Func1Exception e1) {

} catch (Func2Exception e2) {

} catch (Func3Exception e3) {

} finally {
  //shared finally
}

another option is use an to track which function has executed

var functionExecuted = -1;
try
{
 Function1();
 functionExecuted = 1;

 Function2();
 functionExecuted = 2;

 Function3();
 functionExecuted = 3;
} catch(Exception e) {

} finally {
  // functionExecuted indicates the last executed function
}

another option is to write a finally function that is called from the individual finally's -- but that strikes me as weird.

Upvotes: 1

zmbq
zmbq

Reputation: 39029

Sure. Just wrap the try/catch with one try/finally.

try
{
    try
    {
    }
    catch ...
    try
    { }
    Catch ...
 }
 finally 
 {
 }

Upvotes: 5

Joel
Joel

Reputation: 16664

No, the finally only applies to the last try/catch block.

Upvotes: 2

Jordão
Jordão

Reputation: 56507

The finally is only applicable to the last try in your example.

It's also not a good idea to have empty catch blocks, as it's akin to swallowing bugs.

Upvotes: 7

Related Questions