Wednesday, December 27, 2006

Throw vs Throw ex

A common mistake a lot of new .Net developers do is using Throw ex instead of just Throw. The difference between Throw ex and Throw is very simple but can cause major headaches when it comes to maintenance. If you use Throw ex it overwrites the stack trace this makes it very hard to find the original line of the thrown exception as you can see in the example I have provided.
Public Class Form1
Private Sub ThrowsExceptions()
Throw New System.Exception("Exception Thrown") 'Line 3
End Sub
Private Sub JustThrowIT()
Try
ThrowsExceptions()
Catch ex As Exception
Throw 'Line 9
End Try
End Sub
Private Sub ThrowEX()
Try
ThrowsExceptions()
Catch ex As Exception
Throw ex 'Line 16
End Try
End Sub
Private Sub ThrowEX_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Try
ThrowEX() 'Line 21
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub

Private Sub JustThrowIt_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
Try
JustThrowIT() 'Line 29
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
End Class

When you click the Throw ex button you get only get references to two lines 16 and 21 the orginal line the exception is thrown is missing(line 3).



When you click the Throw button you get the full stack trace including the line of the orginal exception that was thrown.



Download Source.
throwDemo.zip (47.73 KB)
#     Comments [4]  
kick it on DotNetKicks.com