Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception 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
}
like image 913
schrödingers cat Avatar asked Mar 25 '10 09:03

schrödingers cat


1 Answers

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 (...)
    {
        ...
    }
}
like image 132
Kent Boogaart Avatar answered Sep 20 '22 03:09

Kent Boogaart