Phuc
Phuc

Reputation: 743

"Before the `catch` block is executed, the runtime checks for `finally` blocks.", what does it mean?

From official document about the exception handling:

Before the catch block is executed, the runtime checks for finally blocks.

I feel like the author want to say: "the finally blocks are executed before the catch block".

But this code does the opposite:

try
{
    throw new Exception();
}
catch (Exception e)
{
    Console.WriteLine("In the catch block.");
}
finally
{
    Console.WriteLine("In the finally block.");
}
// Output:
// In the catch block.
// In the finally block.

What does that statement really mean?

Upvotes: 3

Views: 72

Answers (2)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239814

It's very ambiguously worded. What they were trying to indicate is that any finally blocks of any nested try blocks1 (that didn't have a matching catch block for the exception) will be executed, then the catch block that matched the exception (and then its own finally, obviously, unless it throws another exception that is uncaught and the runtime is torn down, which can happen).

This prints A, B, C:

try {
  try {
    throw new Exception();
  }
  catch (ArgumentOutOfRangeException ex)
  {
    Console.WriteLine("No!");
  }
  finally
  {
    Console.WriteLine("A");
  }
}
catch (Exception ex2)
{
  Console.WriteLine("B");
}
finally
{
  Console.WriteLine("C");
}

The clue it's not talking about it's own finally is that it refers to finally blocks - a plural. Since each try can only have one finally, it must be referring to other finally blocks.


1Whether within the try block itself or inside other code called by the try.

Upvotes: 2

nvoigt
nvoigt

Reputation: 77364

This is a "bug" in the documentation. The issue was filed here.

The appropriate catch block (if any) is executed before a potential finally block of the same try-catch-finally construct.

Upvotes: 2

Related Questions