views:

136

answers:

4

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...
        {}


     }
+3  A: 

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.

Matthew Jones
yes I'm completely sorry, the else is wrong, I edited my code, there was nos else, I'm sorry...
Yaelle
+1  A: 

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

David
this was the only thing to do.but now I learned that when you need to do things that are really far-fetched, it might be due to some weakness in the functional and conceptual model of your code... so shame on me!
Yaelle
A: 

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.

Cylon Cat
+2  A: 

Are you looking for this?

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

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

dtb
the problem in this solution is I can't target a specific instruction with my try but I have to embrace a lot of instructions whereas I want a specific instruction to be caught in the calling method...
Yaelle
@user313176: Answer updated. What about this?
dtb