0

我怎样才能做到这一点 ?

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


     }
4

4 回答 4

3

这是不正确的逻辑。如果代码进入 if 语句,则不会执行 else 块。

如果您真的需要在异常情况下执行它,请将 else 块中的代码复制到 finally 块中。

编辑:所以我认为你想要的是:

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

其背后的原因是,如果 IF 语句为真,内部 try 将执行代码,如果遇到 ComException,将捕获并重新抛出。无论 IF 语句或 ComException 的捕获如何,finally 块中的代码都将执行。

这是否更好地解释了这个位置?

dtb道歉;他先回答了这个,我只是添加了一个解释。

于 2010-04-09T20:57:40.213 回答
2

将“else”分支中的代码移动到单独的方法中。然后从“else”和“finally”调用该方法。

于 2010-04-09T20:57:47.627 回答
2

你在找这个吗?

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

无论条件是否成立,都会执行 finally 块。

于 2010-04-09T20:59:37.143 回答
0

如果需要执行某些东西,它必须进入 finally 块。无论 try 和 catch 块中发生什么,finally 总是执行。“else”的上下文实际上在您的 try/catch/finally 段之外。

于 2010-04-09T20:57:56.693 回答