Thursday, March 02, 2006

Throwing Exceptions

Don't do this:

1 Public Sub DoTask()

2 Throw New NotImplementedException

3 End Sub

4

5 Public Sub LogError(ByVal ex As Exception)

6 'TODO: log the error

7 End Sub

8

9 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

10 Try

11 DoTask()

12 Catch ex As Exception

13 LogError(ex)

14 Throw ex

15 End Try

16 End Sub



Do this:

The reason for this is calling throw ex wipes out the stack trace

The output of the first example using throw ex would be:

Unhandled Exception: System.NotImplementedException: The method or operation is not implemented.
at WindowsApplication1.Form1.Button1_Click(Object sender, EventArgs e) in C:\...\Form1.vb:line 70


Whereas with just using throw:

Unhandled Exception: System.NotImplementedException: The method or operation is not implemented.
at WindowsApplication1.Form1.DoTask() in C:\...\Form1.vb:line 58
at WindowsApplication1.Form1.Button1_Click(Object sender, EventArgs e) in C:\...\Form1.vb:line 70


By using Throw ex it looks like the exception occured in the method that throws it. By using Throw you can perserve all of the stack trace information and easily see where the error came from.

0 Comments:

Post a Comment

<< Home