如何将异常抛给下一个捕获?

Exp*_* be 19 c# exception-handling exception

在此输入图像描述

我想在下一次捕获时抛出异常,(我附图)

有人知道怎么做吗?

Jon*_*eet 29

你不能,并试图这样做表明你的catch块中有太多的逻辑,或者你应该重构你的方法只做件事.如果你不能重新设计它,你将不得不嵌套你的try块:

try
{
    try
    {
        ...
    }
    catch (Advantage.Data.Provider.AdsException)
    {
        if (...)
        {
            throw; // Throws to the *containing* catch block
        }
    }
}
catch (Exception e)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)


l33*_*33t 29

C# 6.0 救援!

try
{
}
catch (Exception ex) when (tried < 5)
{
}
Run Code Online (Sandbox Code Playgroud)

  • 现在是正式的!我比Jon Skeet好:P (4认同)

Hon*_*tan 12

一种可能性是嵌套try/catch子句:

try
{
    try
    {
        /* ... */
    }
    catch(Advantage.Data.Provider.AdsException ex)
    {
        /* specific handling */
        throw;
    }
}
catch(Exception ex)
{
    /* common handling */
}
Run Code Online (Sandbox Code Playgroud)

还有另一种方法 - 只使用你的常规catch语句并自己检查异常类型:

try
{
    /* ... */
}
catch(Exception ex)
{
    if(ex is Advantage.Data.Provider.AdsException)
    {
        /* specific handling */
    }

    /* common handling */
}
Run Code Online (Sandbox Code Playgroud)