views:

121

answers:

2

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
}
+8  A: 

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

HTH,
Kent

Kent Boogaart
A: 

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()
   }
}
balexandre
Surely only appropriate to have this if it is possible to do something constructive with an exception raised from that method. Catching it when there is nothing appropriate to do is pretty useless.
Paddy
@Paddy You should at least LOG it for later review on why it raised an Exception...
balexandre
@balexandre I would say that depends on how your system is set up to handle exceptions - in some cases it makes more sense to allow the exception to bubble up and leave the outer layer of the system to log all exceptions, rather than cluttering up your code with logging lines. If you swallow the exception, you should definitely log it, however.
Paddy
try / catch is a statement not a method, and try / finally is always preferred, unless the current method is well-placed for handling the expected exception, which is not usual. Also, no code should ever catch the base Exception object, unless it is at the topmost level or the application's unhandled exceptions handler for the purpose of logging.
Jeffrey L Whitledge