2010-06-12 38 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,「奇招」),因爲它似乎處理它比它強迫爲字符串更好。