Search code examples
vb.netvisual-studiocompiler-errorsclosuresvisual-studio-2022

VB.NET silently fails to compile code with `On Error Resume Next` + capturing closures


The following VB.NET console app fails to compile, and VS2022 doesn't show any error / warning:

Module Program
    Sub Main()
        On Error Resume Next                    '0
        Dim a As String
        Dim b = Sub(_a) Console.WriteLine(_a)   '1
        Dim c = Sub(_a) a = _a                  '2
    End Sub
End Module

Commenting out line '0 makes the program work, and so does commenting out '2.

'0 and '1 can work together, but '0 and '2 can't.


P.S. No need to tell me that On Error Resume Next is not recommended - I wouldn't like to use it. In fact, I personally prefer C# over VB.NET.

I'm just toying with VB to illustrate an idea that Golang-style error handling with if err != nil checks read just like legacy VB-style If Err.GetException() IsNot Nothing Then with On Error Resume Next being active.


Solution

  • I just copied your code and built the project and got this in the Output window:

    error BC36595: Method cannot contain both a 'On Error Resume Next' statement and a definition of a variable that is used in a lambda or query expression.

    I don't know the inner workings of lambdas well enough to know exactly why that would be an issue but the error message is pretty clear.