MGBrown.com

Fail Fast and Re-throwing Exceptions

Martin Fowler has published an article by Jim Shore that describes why software should "Fail Fast". I guess that, as an experienced programmer, I was subconsciously aware of this. However, it is always useful to have these things knocked to the front of your consciousness.

Given the .Net bent of this site, I thought I would add a little bit on the subject of re-throwing exceptions. I have often come across code with catch blocks that look like this one:

Try
    Sub1()
Catch ex As Exception
    Throw ex
End Try

This is bad and not just because it does not seem to do anything useful. This code actually makes finding the source of an exception a whole lot harder. The reason for this is that the Exception object contains a stack trace. When you re-throw that exception as I did in the example above .Net restarts the stack trace from the point at which it is re-thrown.

For example with the code given in Example 1 at the end of this post, pressing Button1 will give this stack trace:

at WindowsApplication2.Form1.Sub1()
    in C:My ProjectsWindowsApplication2Form1.vb:line 100
at WindowsApplication2.Form1.Button1_Click(Object sender, EventArgs e)
    in C:My ProjectsWindowsApplication2Form1.vb:line 81

Note that this does not tell us whether it was Sub3 or Sub4 that failed. This is because Sub1 uses 'throw ex' which restarts the stack trace. Button2, which just uses 'throw', however gives us something far more helpful:

at WindowsApplication2.Form1.Sub3()
    in C:My ProjectsWindowsApplication2Form1.vb:line 114
at WindowsApplication2.Form1.Sub2()
    in C:My ProjectsWindowsApplication2Form1.vb:line 109
at WindowsApplication2.Form1.Button2_Click(Object sender, EventArgs e)
    in C:My ProjectsWindowsApplication2Form1.vb:line 89

Example 1:


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Try
        Sub1()
    Catch ex As Exception
        txtResult.Text = ex.StackTrace
    End Try
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    Try
        Sub2()
    Catch ex As Exception
        txtResult.Text = ex.StackTrace
    End Try
End Sub

Private Sub Sub1()
    Try
        Sub3()
        Sub4()
    Catch ex As Exception
        Throw ex
    End Try
End Sub

Private Sub Sub2()
    Try
        Sub3()
        Sub4()
    Catch ex As Exception
        Throw
    End Try
End Sub

Private Sub Sub3()
    Throw New System.ApplicationException("I threw an error")
End Sub

Private Sub Sub4()
    Return
End Sub

Comments

Sorry, this post is no longer accepting comments.