Reputation: 47
I have a function which returns datatable
Private Function _Read() As DataTable
Dim _cmd As New SqlCommand
Dim _da As New SqlDataAdapter(_cmd)
Dim _dt As New DataTable
With _cmd
.Connection = dbRoot
.CommandTimeout = 0
.CommandText = "SELECT * FROM Table "
End With
Try
_da.Fill(_dt)
Return _dt
Catch ex As Exception
Return Nothing
End Try
End Function
Now i want to get control if error ocurs so i put the code inside the Try Catch block.
How can i check from my program did exception happend ?
Can i set like this
IF _Read = nothing ?
Upvotes: 0
Views: 8687
Reputation: 404
Try below variation of _Read method. This method returns DataTable as return type and error message as output parameter. I hope this will help.
Private Function _Read(ByRef errorMsg As String) As DataTable
Try
'Get data from datrabase
'return datatable
_Read = New Data.DataTable
'return empty if no error occured
errorMsg = ""
Catch ex As Exception
'return null data table
_Read = Nothing
'return error code
errorMsg = ex.Message
End Try
End Function
Call this method in you code as
Dim myDataTable As Data.DataTable
Dim myErrorMsg As String = ""
myDataTable = _Read(myErrorMsg)
If myErrorMsg <> "" Then
MessageBox.Show(myErrorMsg)
End If
Upvotes: 1
Reputation: 1658
First, to check if _Read returned nothing, you have to use the Is keyword in vb.net :
If _Read Is nothing Then
...
End if
But If you really want to "get control if error occurs" then the first thing you have to do is apply proper error handling. Never catch and ignore exceptions. A way to handle the exception is to notify the user through a message box, log it. Another option is not to have a Catch in the procedure so that the error is propagated up the stack.
Also, you may want to have a finally block to close and release resources, or use a using construct. See here : SqlCommand (Using Statement / Disposing issue)
Upvotes: 1