schrödingers cat
schrödingers cat

Reputation: 131

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
}

Upvotes: 5

Views: 756

Answers (1)

Kent Boogaart
Kent Boogaart

Reputation: 178790

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 (...)
    {
        ...
    }
}

Upvotes: 11

Related Questions