不鼓励简单地抓住System.Exception.相反,只应捕获"已知"异常.
现在,这有时会导致不必要的重复代码,例如:
try
{
WebId = new Guid(queryString["web"]);
}
catch (FormatException)
{
WebId = Guid.Empty;
}
catch (OverflowException)
{
WebId = Guid.Empty;
}
Run Code Online (Sandbox Code Playgroud)
我想知道:有没有办法捕获两个异常并且只WebId = Guid.Empty调用一次呼叫?
给出的例子相当简单,因为它只是一个GUID.但是想象一下你多次修改一个对象的代码,如果其中一个操作以预期的方式失败,你想要"重置"它object.但是,如果出现意外异常,我仍然希望将其提高.
使用C#,是否有更好的方法来处理多种类型的异常,而不是一堆丑陋的catch块?
什么是这种情况的最佳做法?
例如:
try
{
// Many types of exceptions can be thrown
}
catch (CustomException ce)
{
...
}
catch (AnotherCustomException ace)
{
...
}
catch (Exception ex)
{
...
}
Run Code Online (Sandbox Code Playgroud)