25

在此处输入图像描述

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

有人知道怎么做吗?

4

4 回答 4

41

C# 6.0救援!

try
{
}
catch (Exception ex) when (tried < 5)
{
}
于 2015-12-30T23:29:29.403 回答
33

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

try
{
    try
    {
        ...
    }
    catch (Advantage.Data.Provider.AdsException)
    {
        if (...)
        {
            throw; // Throws to the *containing* catch block
        }
    }
}
catch (Exception e)
{
    ...
}
于 2012-11-26T21:15:50.260 回答
14

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

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

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

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

    /* common handling */
}
于 2012-11-26T21:20:22.237 回答
0

这个答案的灵感来自Honza Brestan 的回答

}
catch (Exception e)
{
  bool isAdsExc = e is Advantage.Data.Provider.AdsException;

  if (isAdsExc)
  {
    tried++;
    System.Threading.Thread.Sleep(1000);
  }

  if (tried > 5 || !isAdsExc)
  {
    txn.Rollback();
    log.Error(" ...
    ...
  }
}
finally
{

try将两个块相互嵌套在一起很丑。

如果您需要使用 的属性AdsException,请使用强制转换as而不是is.

于 2012-11-26T22:47:34.277 回答