Syl*_* B. 3 c# exception-handling exception
我想编写一个处理异常的方法,并在catch块内调用.根据传递的异常的类型,异常要么作为新异常的内部异常传递,要么只是重新抛出.如何在第二种情况下保留堆栈跟踪?
示例:
public void TestMethod()
{
try
{
// can throw an exception specific to the project or a .Net exception
SomeWorkMethod()
}
catch(Exception ex)
{
HandleException(ex);
}
}
private void HandleException(Exception ex)
{
if(ex is SpecificException)
throw ex; //will not preserve stack trace...
else
throw new SpecificException(ex);
}
Run Code Online (Sandbox Code Playgroud)
我不想做的是,因为模式在很多地方重复,并且没有因子分解:
try
{
SomeWorkMethod();
}
catch(Exception ex)
{
if(ex is SpecificException)
throw;
else
throw new SpecificException(ex);
}
Run Code Online (Sandbox Code Playgroud)
您需要在throw不指定异常的情况下使用以保留堆栈跟踪.这只能在catch块内完成.您可以做的是返回HandleException而不抛出原始异常,然后立即使用throw:
public void TestMethod()
{
try
{
// can throw an exception specific to the project or a .Net exception
SomeWorkMethod()
}
catch(Exception ex)
{
HandleException(ex);
throw;
}
}
private void HandleException(Exception ex)
{
if(ex is SpecificException)
return;
else
throw new SpecificException(ex);
}
Run Code Online (Sandbox Code Playgroud)
只要您仅用于is对异常进行分类,首选方法是两个catch块:
public void TestMethod()
{
try
{
// can throw an exception specific to the project or a .Net exception
SomeWorkMethod()
}
catch (SpecificException)
{
throw;
}
catch(Exception ex)
{
throw new SpecificException(ex);
}
}
Run Code Online (Sandbox Code Playgroud)
使用C#6.0,您还可以使用when异常来解决:
public void TestMethod()
{
try
{
// can throw an exception specific to the project or a .Net exception
SomeWorkMethod()
}
catch(Exception ex) when (!(ex is SpecificException))
{
throw new SpecificException(ex);
}
}
Run Code Online (Sandbox Code Playgroud)