I was using the following to provide more information on a common 开发者_开发百科exception that can occour in a piece of my code, the only problem is this errors if an exception is generated that has no InnerException message.
Catch ex As Exception
'MessageBox.Show(ex.Message) 'If there is no InnerException.
MessageBox.Show(ex.InnerException.InnerException.Message)
End Try
Is there a better method of doing this?
You can make a recursive function to keep grabbing the inner exceptions as long as they exist, that way you will get the full details if you have a single exception or 3 exceptions layered within each other.
Public Function ReadException(ByVal ex As Exception) As String
Dim msg As String = ex.Message
If ex.InnerException IsNot Nothing Then
msg = msg & vbCrLf & "---------" & vbCrLf & ReadException(ex.InnerException)
End If
Return msg
End Function
and in your catch:
Catch ex As Exception
MessageBox.Show(ReadException(ex))
End Try
Just surround it by an If not nothing, but if you're doing it a lot, write a quick helper function like:
Private Function GetErrorText(ByVal ex As Exception) As String
Dim err As String = ex.Message
If ex.InnerException IsNot Nothing Then
err &= " - More details: " & ex.InnerException.Message
End If
Return err
End Function
Then you can just do MessageBox.Show(GetErrorText(ex))
.
精彩评论