« Back to blog

Throw command difference in C# and VB.NET

Have you ever noticed that throw command behaves somewhat differently in VB.NET and C#? See the following two code parts. It's the same thing written in VB.NET and C#. DummyMethod throws an exception (line 12) that is caught by a try/catch statement in the Main method. Line 7 writes the exception into the console window.

1: static void Main(string[] args) {
2:  try
3:  { DummyMethod(); }
4:  catch (Exception ex)
5:  { Console.WriteLine(ex);
6:  }
7:  Console.ReadKey();
8: }
9:  
10: private static void DummyMethod() {
11:  try
12:  { throw new Exception("Dummy Exception"); }
13:  catch (Exception ex)
14:  { throw ex;
15:  }
16: }
1: Sub Main()
2:  Try
3:  DummyMethod()
4:  Catch ex As Exception
5:  Console.Write(ex)
6:  End Try
7:  Console.ReadKey()
8: End Sub
9:  
10: Private Sub DummyMethod()
11:  Try
12:  Throw New Exception("Dummy Exception")
13:  Catch ex As Exception
14:  Throw ex
15:  End Try
16: End Sub

If you execute both pieces of code in Release configuration you see in your console window that the exception was thrown by line 14. Now remove the underlined ex variable from line 14, so that Throw command is left alone. If you execute the code now (still in Release configuration) C# code will write that the exception was thrown by line 14 again, but VB.NET code will write that exception was thrown by line 12!

Click here to download:
ExceptionTest._zip (9 KB)

Comments (0)

Leave a comment...