Joe Duffy's excellent blog has just taught me something (in guideline 16 of this article) that I didn't know about structured exception handling in VB.NET, and which is not explained in the language spec (see 10.10.1).
What do you think this code should do?
2 Module Module1
4 Private _value As Integer
6 Sub Main()
7 _value = 42
10 Catch ex As Exception When _value = 7
11 MsgBox("Oh, that's all right then.")
12 Catch ex As Exception
13 MsgBox("The non-7 value is: " & _value.ToString)
14 End Try
15 End Sub
17 Sub Trouble()
19 Throw New Exception
21 _value = 7
22 End Try
23 End Sub
25 End Module
It prints "The non-7 value is: 7" of course.
Without a great deal of research (i.e. none) it seems the two passes mentioned by Joe are:
- find the target of the exception (i.e. the closest matching catch block on the stack);
- transfer control to that catch block via each finally block between it and the throw point.
Therefore no finally-block code will have executed when the When clause is executed, so invariants could still be broken.
No big deal (since exception filters should be kept simple), but worth knowing.