Wednesday, November 10, 2004

I found this on statement on the Microsoft site that helps clarify the issue I discovered earlier.
Best Practices for Handling Exceptions: "The stack trace begins at the statement where the exception is thrown and ends at the catch statement that catches the exception. Be aware of this fact when deciding where to place a throw statement. "
I was trying to track down an issue I was having with Encompass and was trying to find it based on the stack trace I had. The stack trace was very 'shallow', all I could tell was where the last error was 'rethrown' in a Catch statement.
I discovered that I was using exceptions incorrectly :(

Take for instance this code snippet:


Private Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Click
Try
testthrow()
Catch ex As Exception
Dim msg As String
Dim innr As Exception
msg = ex.Message & vbCrLf & "---" & vbCrLf & ex.StackTrace
innr = ex.InnerException
While Not (innr Is Nothing)
msg &= vbCrLf & innr.Message & vbCrLf & "---" & vbCrLf & innr.StackTrace
innr = innr.InnerException
End While
MsgBox(msg)
End Try
End Sub
Private Sub testthrow()
Try
testthrow2()
Catch ex As Exception
Throw

Finally
Debug.WriteLine("finally")
End Try
End Sub
Private Sub testthrow2()
Throw New Exception("Eeek!")
End Sub

The problem code is highlighted in yellow. When the exception is rethrown, the stack trace from the caller (in this case testthrow) is lost! In fact, the stack trace indicates the error occurred in the rethrowing catch block.

The correct way to handle this is to throw a new exception, with the 'caught' expection being set as the inner exception of it.

Catch ex As Exception
Throw New Exception("Better exception", ex)


Tuesday, November 09, 2004

I'm doing a magic show on Saturday and was asked to do balloon animals. I thought "Why not, it can't be that hard". Hmm... I was wrong. It's harder than learning a Zarrow Shuffle.