很多catch块,但在所有catch块中都有相同的功能

sil*_*lla 6 .net c# exception try-catch

如果我有这样的事情怎么办?

try
{
   //work
}
catch (ArgumentNullException e)
{
   HandleNullException();
   Logger.log("ArgumentNullException " + e);
   DoSomething();
}
catch (SomeOtherException e)
{
   HandleSomeOtherException();
   Logger.log("SomeOtherException " + e);
   DoSomething();
}
catch (Exception e)
{
   HandleException();
   Logger.log("Exception " + e);
   DoSomething();
}
Run Code Online (Sandbox Code Playgroud)

现在我们可以看到,我正在尝试处理一些不同情况的异常.但是每当引发异常时,我总是DoSomething()在最后调用该方法.DoSomething()如果有异常,是否有更聪明的方式来调用?如果我添加了一个finally块并DoSomething()在那里调用,它将始终被调用,即使没有异常.有什么建议?

sta*_*ica 9

如果我添加了一个finally块并DoSomething()在那里调用,它将始终被调用,即使没有异常.

您正在寻找的内容在CLI标准(分区IIA,第18章)中称为故障处理程序.尽管.NET实现了它们,但C#语言并不直接支持它们.但是,可以模拟它们:

bool success = false;
try
{
    …
    success = true;
}
catch (…)
{
    …
}
…
finally
{
    if (!success)
    {
        DoSomething();
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,不需要在每个catch处理程序中设置标志,因为这里的一些答案建议.简单地否定测试,您只需要在try块结束时设置一次标志.


Mir*_*Mir 5

您可以使用下面的代码实际上确实消除冗余.

try
{
    //work
}
catch (Exception e)
{
    Handle(e);
}
Run Code Online (Sandbox Code Playgroud)

Handle方法是:

static void Handle(Exception e)
{
    var exceptionType = e.GetType();
    //Use an if/else block, or use a Dictionary<Type, Action>
    //to operate on your exception
    Logger.log(exceptionType + " " + e);
    DoSomething();
}
Run Code Online (Sandbox Code Playgroud)