A colleague found a wired debugger behavior in in his VB.net solution. I confess this will be more an academic question as this only effects the sequence of highlighted statements while debugging and not the overall behavior of the code. So for all curious out there:
We stripped down this to the following minimum console application:
Private Sub PlayWithExceptions
Dim a = 2
Try
throw new Exception("1")
Catch ex As Exception
If a = 2 Then
Dim x = New XElement("Dummy")
Else
throw
End If
End Try
End Sub
Sub Main()
Try
PlayWithExceptions()
Catch ex As Exception
End Try
End Sub
As obvious the debugger throws Exception(“1”) and the debugger jumps into the catch clause of PlayWithExceptions method. There, as “a” is always 2, the debugger jumps to some dummy code (New XElement…), from there to the “End If” and finally back into the Else-leaf onto the throw statement. I confess that Visual Studio does not re-throw the exception, but nevertheless it looks very strange.
Changing the condition “If a = 2” into “If True” eliminates this behavior.
Refactoring to conditional catches eliminates this behavior too.
Private Sub PlayWithExceptions
Dim a = 2
Try
throw new Exception("1")
Catch ex As Exception When a = 2
Dim x = New XElement("Dummy")
Catch ex As Exception
throw
End Try
End sub
Translating these few lines into C# does not show this behavior as well.
private static void PlayWithExceptions()
{
var a = 2;
try
{
throw new Exception("1");
}
catch (Exception)
{
if (a == 2)
{
var x = new XElement("Dummy");
}
else
{
throw;
}
}
}
static void Main(string[] args)
{
try
{
PlayWithExceptions();
}
catch (Exception ex)
{
}
}
We tried .Net3.5 and .Net4.6 as well as the targets AnyCPU and x86 without any effect to the above VB-code. The code was executed with the default Debug settings and no further optimizations. We used VS2015 Update 3.
Has anyone an idea why Visual Studio pretends to re-throw the exception in VB (but without really re-throwing it)? It looks confusing while debugging…