Question

how can I do that ?

 void x()
     {....
        if (...)
        {try
            {}
            catch (ComException com)
                { throw com}
            finally  // in any case, executed fine!
                {...instructions.......}

        }
        ... instructions...// not executed in case of exception because the finally can't embrace the following code too... but this block of code needs to be executed in any case too...
        {}


     }
Was it helpful?

Solution

Move the code in the "else" branch to a separate method. Then call that method from both the "else" and the "finally".

OTHER TIPS

That's incorrect logic. The else block will not be executed if the code goes into the if statement.

If you really need it to be executed even in case of exception, copy the code from the else block into the finally block.

EDIT: So I think what you want is this:

try
{
     if()
     {
           try
           {
               //Code
           }
           catch(ComException e)
           {
                throw e;
           }
     }
}
finally
{
    /*....instructions.....*/
}

The reasoning behind this is that the inner try will execute the code if the IF statement is true, and will catch and then re-throw the ComException if it encounters it. The code in the finally block will execute regardless of either the IF statement or the catching of a ComException.

Does this explain the position better?

With apologies to dtb; he answered this first, I just added an explanation.

Are you looking for this?

try
{
    if (...)
    {
        try
        {
            ...
        }
        catch (ComException)
        {
            ...
        }
    }
}
finally
{
    ...
}

The finally block is executed regardless of whether the condition holds or not.

If something needs to be executed, it must go in the finally block. Finally always executes, no matter what happens in try and catch blocks. The context of the "else" is really outside your try/catch/finally segment.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top