How to walk through InnerExceptions?

  • Thread starter Thread starter Terry Olsen
  • Start date Start date
T

Terry Olsen

How can I walk through the InnerExceptions? Would the following code be
correct?

Private Sub ShowException(ByVal ex As Exception)
MsgBox(ex.Message)
If ex.InnerException Is Nothing = False Then _
ShowException(ex.InnerException)
End Sub

I thought I saw a snippet a while ago using a For...Each loop, but I'm
unable to find it again.
 
Hello Terry,

I've not had call to walk over inner exceptions, however, if you really want
to, then you'll need to use a recursive function.

Private Function GetInnerException(byref tException As Exception) As String

Dim tReturn As String = String.Empty

If Not Nothing Is tException Then

tReturn = tException.ToString()

If Not Nothing Is tException.InnerException Then
tReturn = tReturn & GetInnerException(tException.InnerException)
End If

End If

Return tReturn

End Function
 
No, there is no need for a recursive function. It can be done just as
easily using a simple loop:

Private Function GetInnerException(byref tException As Exception) As String

Dim tReturn As String = String.Empty

Do While Not tException Is Nothing
tReturn &= tException.ToString()
tException = tException.InnerException
Loop

Return tReturn

End Function


Save the recursion for when it's useful. :)
 
Thanks. I knew recursion wasn't necessary because I'd seen it before
done this way.
 
Hello Göran,

No no no. tException is declared ByRef. You dont wanna be changing it's
value willy-nilly like that. If you want to use a loop like that then pass
the exception ByVal.

-Boo
 
You are right. I didn't notice the byref when I copied the code. There
is no reason to send the reference to the exception by reference. Simply
remove the byref from the method:

Private Function GetInnerException(tException As Exception) As String

Dim tReturn As String = String.Empty

Do While Not tException Is Nothing
tReturn &= tException.ToString()
tException = tException.InnerException
Loop

Return tReturn

End Function
 
Back
Top