How to walk through InnerExceptions?

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.
 
G

GhostInAK

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
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

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

Terry Olsen

Thanks. I knew recursion wasn't necessary because I'd seen it before
done this way.
 
G

GhostInAK

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
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top