How to throw exception to next catch?

落爺英雄遲暮 提交于 2020-11-26 07:01:46

问题


enter image description here

I want to throw an exception at next catch, (I attached image)

Anybody know how to do this?


回答1:


You can't, and trying to do so suggests that you've got too much logic in your catch blocks, or that you should refactor your method to only do one thing. If you can't redesign it, you'll have to nest your try blocks:

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



回答2:


C# 6.0 to the rescue!

try
{
}
catch (Exception ex) when (tried < 5)
{
}



回答3:


One possibility is nesting the try/catch clause:

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

there is also another way - using only your general catch statement and checking the exception type yourself:

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

    /* common handling */
}



回答4:


This answer is inspired by Honza Brestan's answer:

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

It's ugly to have two try blocks nested inside each other.

If you need to use properties of the AdsException, use an as cast instead of is.



来源:https://stackoverflow.com/questions/13573244/how-to-throw-exception-to-next-catch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!