来自finally块的异常

时间:2010-03-25 09:01:17

标签: c# exception try-catch finally

考虑以下代码,其中LockDevice()可能会失败并在ist上抛出异常。如果从finally块中引发异常,C#中会发生什么?

UnlockDevice();

try
{
  DoSomethingWithDevice();
}
finally
{
  LockDevice(); // can fail with an exception
}

2 个答案:

答案 0 :(得分:10)

如果它不在finally块中会发生完全相同的事情 - 异常可能从那一点传播。如果需要,可以在finally中尝试/ catch:

try
{
    DoSomethingWithDevice();
}
finally
{
    try
    {
        LockDevice();
    }
    catch (...)
    {
        ...
    }
}

答案 1 :(得分:-2)

该方法称为 Try / Catch

  

哪里是你的捕获?

UnlockDevice();

try
{
  DoSomethingWithDevice();
}
catch(Exception ex)
{
  // Do something with the error on DoSomethingWithDevice()
}
finally
{
   try
   {
      LockDevice(); // can fail with an exception
   }
   catch (Exception ex)
   {
       // Do something with the error on LockDevice()
   }
}