【问题标题】:Reuse catch for all catches对所有捕获重复使用捕获
【发布时间】:2013-05-30 15:27:56
【问题描述】:

是否可以执行以下操作:

我想捕获一个自定义异常并用它做点什么 - 很简单:try {...} catch (CustomException) {...}

但是我想运行“catch all”块中使用的代码仍然运行一些与所有catch块相关的其他代码......

try
{
    throw new CustomException("An exception.");
}
catch (CustomException ex)
{
    // this runs for my custom exception

throw;
}
catch
{
    // This runs for all exceptions - including those caught by the CustomException catch
}

或者我是否必须在所有异常情况下将我想做的任何事情(finally 不是一个选项,因为我希望它只针对异常运行)到一个单独的方法/将整个 try/catch 嵌套在另一个(这样)...?

【问题讨论】:

  • 在 catch 语句中设置一个标志并使用“finally”对你有用。或者,将所有公共代码分解为 CleanUpAfterException 方法,并在每个 catch 语句的末尾调用它。
  • 啊 - 设置标志和“终于”似乎是一种巧妙的解决方案。我没想到。

标签: c# try-catch


【解决方案1】:

我通常会做一些类似的事情

try
{ 
    throw new CustomException("An exception.");
}
catch (Exception ex)
{
   if (ex is CustomException)
   {
        // Do whatever
   }
   // Do whatever else
}

【讨论】:

  • 我想这是最整洁的......至少 try 块也没有缩进。碰巧在这两种情况下我只有一个方法调用要做,所以单独的方法不会获得任何东西。
【解决方案2】:

你需要使用两个try 块:

try
{
    try
    {
        throw new ArgumentException();
    }
    catch (ArgumentException ex)
    {
        Console.WriteLine("This is a custom exception");
        throw;
    }
}
catch (Exception e)
{
    Console.WriteLine("This is for all exceptions, "+
        "including those caught and re-thrown above");
}

【讨论】:

  • 我想到了这个,不过似乎有点乱——很多嵌套!
【解决方案3】:

只需进行整体捕获并检查异常是否属于该类型:

try
{
   throw new CustomException("An exception.");
}
catch (Exception ex)
{
   if (ex is CustomException)
   {
       // Custom handling
   }
   // Overall handling
}

或者,有一个用于整体异常处理的方法,两者都调用:

try
{
   throw new CustomException("An exception.");
}
catch (CustomException ex)
{
    // Custom handling here

    HandleGeneralException(ex);
}
catch (Exception ex)
{
   HandleGeneralException(ex);
}

【讨论】:

    【解决方案4】:

    不,它不会这样做,您要么捕获特定异常(线性)要么概括。如果您希望为所有异常运行某些东西,您需要记录是否抛出异常,可能是什么等,并使用finally,或者其他人为的,可能更“混乱”和冗长的机制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      相关资源
      最近更新 更多