我遇到错误处理问题。通过VB程序,我想向SQL Server 2008 R2表添加一个重复的密钥。我正在使用以下代码:
Public Shared Function AddCatPlanilla(ByVal CatPlanilla As CatPlanilla) As Boolean
Dim connection As SqlConnection = EnterpriseDB.GetConnection
Dim insertStatement As String _ = "INSERT [dbo].[CatPlanilla] " _
& "([CodEmpr], [TipoCatalogo], [CodAsoc], [Descripcion], [DescripcionCorta]) " _
& "VALUES (@CodEmpr, @TipoCatalogo, @CodAsoc, @Descripcion, @DescripcionCorta)"
Dim insertCommand As New SqlCommand(insertStatement, connection)
insertCommand.CommandType = CommandType.Text
insertCommand.Parameters.AddWithValue("@CodEmpr", CatPlanilla.m_CodEmpr)
insertCommand.Parameters.AddWithValue("@TipoCatalogo", CatPlanilla.m_TipoCatalogo)
insertCommand.Parameters.AddWithValue("@CodAsoc", CatPlanilla.m_CodAsoc)
insertCommand.Parameters.AddWithValue("@Descripcion", CatPlanilla.m_Descripcion)
insertCommand.Parameters.AddWithValue("@DescripcionCorta", CatPlanilla.m_DescripcionCorta)
Try
connection.Open()
Dim count As Integer = insertCommand.ExecuteNonQuery()
If count > 0 Then
Return True
Else
Return False
End If
Catch ex As SqlException
Throw ex
Finally
connection.Close()
End Try
End Function
当我想添加重复键时,sqlexception不会捕获错误,并且屏幕上会显示以下信息(停止程序):
System.Data.SqlClient.SqlException occurred
Class=14
ErrorCode=-2146232060
HResult=-2146232060
LineNumber=1
Message=Cannot insert duplicate key row in object 'dbo.CatPlanilla' with unique index
'IX_CatPlanilla'. The duplicate key value is (001, LT, Lima).
The statement has been terminated.
我不知道是什么导致了这个问题,或者SQL服务器配置或Visual Studio配置是否存在问题。
我想强调该程序永远不会跳转到CATCH部分。程序在“Dim count As Integer = insertCommand.ExecuteNonQuery()”行中停止 多么遗憾我无法发送图片,对不起
答案 0 :(得分:1)
您的问题出在这些代码行中
Catch ex As SqlException
Throw ex
此代码块将捕获异常,然后立即重新抛出它。它本质上意味着除了重置堆栈跟踪之外,代码对程序没有任何影响。如果您确实想要捕获程序并防止它崩溃,那么您需要删除Throw ex
行。而是尝试显示消息
Catch ex As SqlException
MessageBox.Show(ex.Message)