markzzz
markzzz

Reputation: 47947

Is there a way to know if finally is executed after a try or a catch?

I think the title explain whole my question.

I'd like to know, where I execute my code on finally statement, if it come from a try or a catch.

Is it possible?

Upvotes: 2

Views: 153

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499770

Well, the simplest approach is:

bool success = false;
try
{
    ...
    // This should be the last statement in the try block
    success = true;
}
catch(...)
{
    ...
}
finally
{
    if (success)
    {
        ...
    }
}

This isn't a specific language feature - it's just using the fact that other than really remarkable situations (asynchronous exceptions, basically), you're not going to get an exception occurring after the assignment to success.

Note that success being false doesn't mean that any of your catch blocks have executed - it could be that an exception was thrown which you're not catching (or that you returned before the end of the try block). Basically it only indicates "reached end of try block" - which is normally all that's needed.

Upvotes: 11

Related Questions