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:
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.
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)

0 Comments:
Post a Comment
<< Home