Leo*_*Nix 14 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,MethodA中的try-catch只是提升异常,但并没有真正处理它.在MethodA中使用try-catch是否有任何优势?换句话说,这种try-catch块之间是否存在差异,而根本不使用它?
在您的示例中,没有任何优势.但有些情况下,最好只是冒出一个特定的例外.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
这允许您轻松识别发生异常的边界.在这种情况下,您需要确保仅针对边界特定的代码抛出边界异常.
| 归档时间: |
|
| 查看次数: |
3350 次 |
| 最近记录: |