c# - 重新抛出无参数 catch 和什么都不做的区别?

标签 c# exception try-catch

假设我在两个不同的程序集中有以下两个类:

//in assembly A
public class TypeA {
   // Constructor omitted
   public void MethodA
   {
     try {
       //do something
     }
     catch {
        throw;
     }
   }
}
//in assembly B
public class TypeB {
   public void MethodB
   {
     try {
       TypeA a = new TypeA();
       a.MethodA();
     }
     catch (Exception e)
       //Handle exception
     }
   }
}

在这种情况下,MethodA 中的 try-catch 只是提升了异常,但并没有真正处理它。在 MethodA 中使用 try-catch 有什么优势吗?换句话说,这种 try-catch block 和根本不使用有区别吗?

最佳答案

在您的示例中,这样做没有任何优势。但在某些情况下,最好只冒出一个特定的异常。

    public void Foo()
    {
        try
        {
            // Some service adapter code

            // A call to the service
        }
        catch (ServiceBoundaryException)
        {
            throw;
        }
        catch (Exception ex)
        {
            throw new AdapterBoundaryException("some message", ex);
        }
    }

这使您可以轻松识别异常发生在哪个边界。在这种情况下,您需要确保仅针对特定于边界的代码抛出边界异常。

关于c# - 重新抛出无参数 catch 和什么都不做的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/717489/

相关文章:

c++ - Do - Try/Catch - While block 内部有 2 个函数

c# - 如何让程序在捕获到异常后重复自身?

C# 比较两个时间间隔之间的时间

c# - 如何启用 Acumatica 中的字段 - 状态为 "shipping"的销售订单?

Windows 家长控制 API 的 C# 示例

c# - Windows Phone 8.1 中的 System.IO 中缺少 FileStream

c# - ExecuteScalar "Specified cast is not valid"异常

c# - MongoDB服务器状态已断开

快速返回或抛出

python - Python 中的华氏度转换器,使用 try/except 命令排除字母