开发者

Exception from within a finally block

开发者 https://www.devze.com 2022-12-24 10:45 出处:网络
Consider开发者_运维百科 the following code where LockDevice() could possibly fail and throw an exception on ist own. What happens in C# if an exception is raised from within a finally block?

Consider开发者_运维百科 the following code where LockDevice() could possibly fail and throw an exception on ist own. What happens in C# if an exception is raised from within a finally block?

UnlockDevice();

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


Exactly the same thing that would happen if it wasn't in a finally block - an exception could propagate from that point. If you need to, you can try/catch from within the finally:

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


The method is called Try / Catch

Where is your 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()
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号