我在错误处理方面遇到问题。通过 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 ()”那一行
可惜不能发图,不好意思
最佳答案
您的问题出在这些代码行中
Catch ex As SqlException
Throw ex
此代码块将捕获异常,然后立即重新抛出它。它本质上意味着代码除了重置堆栈跟踪之外对您的程序没有任何影响。如果你真的想捕获程序并防止它崩溃,那么你需要删除
Throw ex
线。而是尝试显示一条消息Catch ex As SqlException
MessageBox.Show(ex.Message)
关于vb.net - Visual Basic try catch 未捕获的重复键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18370100/