Beware "Exit Try"!

Brad Abrams' recent post about the IL code generated by the C# compiler reminded me of an issue that someone found with the VB.NET "Exit Try" statement. I thought I'd post it here to make sure all three of my subscribers know about this... :)

Mattias Sjogren summed it up in this newgroup posting. The VB.NET compiler generates a try/finally block around For..Each statements. It does this to make sure that the IEnumerator used in the For..Each has it's Dispose method called if it supports IDispose.

In the example from Mattias:

Try
  Console.WriteLine("Before For Each loop")
  For Each i In al
    Console.WriteLine( i )
    If i = 2 Then Exit Try
  Next

  Console.WriteLine("After For Each loop - should never get here")

Finally
  Console.WriteLine("In Finally")
End Try

when the VB.NET compiler sees an "Exit Try", it doesn't realize that the current try/catch block it is inside is a compiler-generated one and not a user-defined one. Therefore, the instruction generated to leave the try/catch block causes execution to jump to the end of the compiler-generated try/catch block -- i.e. the statement after the "Next"! This something you can only see by looking at the IL code. Another reason everyone should become comfortable reading IL.

The solution? Don't use "Exit Try". In my opinion, it's a cousin of GoTo and if you think you need it, reorganize your code and logic so you don't need it. And for those interested, C# does not have an 'exit try' statement so this issue only affects VB.NET.

5 Comments

Comments have been disabled for this content.