执行存储过程时的异常处理

时间:2012-01-15 11:49:34

标签: vb.net sql-server-2005

当我使用下面的函数时,它会显示错误消息,但仍然会显示错误,说明异常未处理。为什么会这样?

Public Function DepartmentDelete(ByVal DepartmentID As Integer) As DataTable

    Try
        Using con As New SqlConnection(CMClass.GetConnectionString())
            Dim ds As DataTable = New DataTable
            con.Open()
            Dim command As SqlCommand = New SqlCommand("Department_Delete", con)
            command.Parameters.AddWithValue("@DepartmentID", DepartmentID)
            command.CommandType = CommandType.StoredProcedure
            Dim adapter As SqlDataAdapter = New SqlDataAdapter(command)
            Dim table As DataTable = New DataTable
            adapter.Fill(ds)
            Return ds
            con.Close()
        End Using
    Catch ex As SqlException
                 Throw New Exception(MsgBox(ex.Message))
        End
    End Try

End Function

1 个答案:

答案 0 :(得分:1)

您的异常处理程序正在捕获SQLException

问题在于处理程序中的以下行:

Throw New Exception(MsgBox(ex.Message))

如果您想要消息框,请使用

MsgBox(ex.Message)

如果您想要冒泡,则应使用

Throw

不要将ex放在Throw的末尾,因为这会创建一个新的异常(特别是完整的堆栈跟踪),而不是重新抛出旧的异常,从而掩盖了实际问题的一些细节。

另外。如果你确实选择重新抛出异常,那么你需要在堆栈的某个地方再次捕获它,否则你仍然会得到未处理的异常消息。

相关问题