来自finally块的异常

sch*_*cat 5 c# exception finally try-catch

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

UnlockDevice();

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

Ken*_*art 10

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

try
{
    DoSomethingWithDevice();
}
finally
{
    try
    {
        LockDevice();
    }
    catch (...)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)