Search code examples
c#lockingmonitor

Why C# Monitor class implementation for lock statement have try-finally only but not catch?


Why C# Monitor class implementation for lock statement have try-finally only but not catch ?

var obj = new object();
try
{
  Monitor.Enter(obj);
}
finally 
{
  Monitor.Exit(obj);
}

Solution

  • You should have posted some code to explain what you mean...

    Generally the reason why you have a finally but no catch is because you have some code you want run when the scope (the try) is exited regardless of how the exit happens.

    In other words, whoever wrote the code doesn't care what exception is thrown (if any) because they are not dealing with it right then (it will just bubble up to the next level of code), but whatever is in the finally will always be run whether there was an exception or not.