2010-06-12 47 views
1

我正在使用以下内容来提供有关可在一段代码中发生的常见异常的更多信息,唯一的问题是如果生成的异常没有InnerException消息,则此错误是唯一的。Display Capture InnerException消息

Catch ex As Exception 
    'MessageBox.Show(ex.Message) 'If there is no InnerException. 
    MessageBox.Show(ex.InnerException.InnerException.Message) 
End Try 

有没有更好的方法来做到这一点?

回答

1

只要存在内部异常,您就可以创建一个递归函数来抓取内部异常,这样,如果您有单个异常或3个异常分层存在,那么您将获得完整详细信息。

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 

,并在你的陷阱:

Catch ex As Exception 
    MessageBox.Show(ReadException(ex)) 
End Try 
1

就围绕着它通过如果没有什么,但如果你做了很多,写这样一个快速的辅助函数:

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 

然后,你可以做MessageBox.Show(GetErrorText(ex))

0

你可以只是做string.concat(ex.InnerException,“奇招”),因为它似乎处理它比它强迫为字符串更好。