开发者

Try Catch - Finally in If statement, how to go on after?

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 followi开发者_开发知识库ng code too... but this block of code needs to be executed in any case too...
        {}


     }


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜