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
Tuesday, January 09, 2007 1:59:55 PM (GMT Standard Time, UTC+00:00)
Is it not better to use
Throw New Exception("Extra Info About Program State", ex)
Buzz
Tuesday, January 09, 2007 4:10:16 PM (GMT Standard Time, UTC+00:00)
What about something like:

Throw New Exception(ex.Message, ex)
Tuesday, January 09, 2007 9:05:23 PM (GMT Standard Time, UTC+00:00)
Great information, thanks. If you run FxCop on your code, you'll notice this is something that is caught. The tool recommends using just throw instead of throw ex.
Tuesday, February 06, 2007 3:25:16 PM (GMT Standard Time, UTC+00:00)
Is it not better to use
Throw New Exception("Extra Info About Program State", ex)


If you mean to put that in the catch block it should work but it is a bit wordy. You may lose some of the stack trace like the exact line the exception was thrown . I prefer just to put just plain throw unless I am at the UI layer.


What about something like:

Throw New Exception(ex.Message, ex)


That looks like it would have the same output but why would you do all that when you can just write "throw" and be done with it.
Aaron
Comments are closed.