如何用 try catch 替换 Dot Net ErrObject
how to replace Dot Net ErrObject with try catch
我已将下面的代码行迁移到 Vb.net,我正在用 try catch 块替换 On Error GoTo。
所以在下面的代码中,如果有任何错误,语句将跳转到 ErrorHandler: label ,它将 dot net ErrObject.error 与 duplicate key 进行比较。如果有重复键,则该行代码将继续执行下一条语句。我如何用 try catch 替换它?
Const DUPLICATE_KEY = 457
On Error GoTo ErrorHandler
'down below there lines of code
ErrorHandler:
'continue if it is a duplicate key
If Err.Number = DUPLICATE_KEY Then 'Duplicate key
Resume Next
end if
要向 DaveInCraz 评论添加更多详细信息,这里有两个示例展示了如何将 VB6 迁移到 VB.NET:
首先,让我们从一个 VB6 示例开始。基本上它是一个带有处理多种错误类型的错误处理程序的子例程。
Sub aSubToMigrate
On Error GoTo ErrorHandler
' Down below there lines of code
ErrorHandler:
'continue if it is a duplicate key
Select Case Err.Number
Case ERROR_CODE_1:
' Error 1 case processing
' [...]
Case ERROR_CODE_2:
' Error 2 case processing
' [...]
Case Else:
' Generic error case processing
End Select
Resume Next
End Sub
VB.NET 中的错误管理处理异常对象抛出和 Try-Catch
块。您可以通过为给定错误类型编写 Catch
块来分别处理每种类型的错误,如下所示:
Sub aMigratedSub
Try
' Down below there lines of code
Catch ex As ExceptionType1
' Error 1 case processing
Catch ex As ExceptionType2
' Error 2 case processing
Catch ex As Exception
' Generic error case processing (Exception is the root class)
End Try
' Code executed after (no need of Resume Next so)
End Sub
当然,不要指望总是为每个 Err.Number
找到唯一的 Exception
class,这不是双射(一对一)关系。
More informations about Try-Catch blocks in the official site of Microsoft.
我已将下面的代码行迁移到 Vb.net,我正在用 try catch 块替换 On Error GoTo。 所以在下面的代码中,如果有任何错误,语句将跳转到 ErrorHandler: label ,它将 dot net ErrObject.error 与 duplicate key 进行比较。如果有重复键,则该行代码将继续执行下一条语句。我如何用 try catch 替换它?
Const DUPLICATE_KEY = 457
On Error GoTo ErrorHandler
'down below there lines of code
ErrorHandler:
'continue if it is a duplicate key
If Err.Number = DUPLICATE_KEY Then 'Duplicate key
Resume Next
end if
要向 DaveInCraz 评论添加更多详细信息,这里有两个示例展示了如何将 VB6 迁移到 VB.NET:
首先,让我们从一个 VB6 示例开始。基本上它是一个带有处理多种错误类型的错误处理程序的子例程。
Sub aSubToMigrate
On Error GoTo ErrorHandler
' Down below there lines of code
ErrorHandler:
'continue if it is a duplicate key
Select Case Err.Number
Case ERROR_CODE_1:
' Error 1 case processing
' [...]
Case ERROR_CODE_2:
' Error 2 case processing
' [...]
Case Else:
' Generic error case processing
End Select
Resume Next
End Sub
VB.NET 中的错误管理处理异常对象抛出和 Try-Catch
块。您可以通过为给定错误类型编写 Catch
块来分别处理每种类型的错误,如下所示:
Sub aMigratedSub
Try
' Down below there lines of code
Catch ex As ExceptionType1
' Error 1 case processing
Catch ex As ExceptionType2
' Error 2 case processing
Catch ex As Exception
' Generic error case processing (Exception is the root class)
End Try
' Code executed after (no need of Resume Next so)
End Sub
当然,不要指望总是为每个 Err.Number
找到唯一的 Exception
class,这不是双射(一对一)关系。
More informations about Try-Catch blocks in the official site of Microsoft.