Error handling in VBA or VB is done using the On Error statements. While the On Error statements can be used with VB.NET without any problems, it is recommended to utilize Try statements instead. Try statements are more flexibility than the On Error Resume Next and On Error GoTo Label statements.
VBA 或 VB 中错误处理是使得 On Error 语句完成的。虽然 On Error 语句用在 VB.NET 中没有任何问题,但还是推荐使用 Try 语句。Try 语句比 On Error Resume Next 和 On Error GoTo Label 语句更灵活。
The use of On Error Resume Next and On Error GoTo Label statements can be rewritten using Try-Catch statements. The following shows how an On Error GoTo Label statement can be rewritten using Try-Catch.
使用On Error Resume Next 和 On Error GoTo Label 语句可以使用Try-Catch 语句重写。下面演示如何利用 Try-Catch 重写On Error GoTo Label 语句。
Sub ColorEntities()
On Error GoTo MyErrorHandler
Dim entry As Object
For Each entry In ThisDrawing.ModelSpace
entry.color = acRed
Next entry
' Important! Exit the subroutine before the error handler
Exit Sub
MyErrorHandler:
MsgBox entry.EntityName + " is on a locked layer." + _
" The handle is: " + entry.Handle
Resume Next
End Sub
<CommandMethod("ColorEntities")> _
Public Sub ColorEntities()
''获得当前文档和数据库,并启动一个事务 Get the current document and database, and start a transaction
Dim acDoc As Document = Application.DocumentManager.MdiActiveDocument
Dim acCurDb As Database = acDoc.Database
Using acTrans As Transaction = acCurDb.TransactionManager.StartTransaction()
'' 以只读方式打开块表记录 Open the Block table record for read
Dim acBlkTbl As BlockTable
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, _
OpenMode.ForRead)
'' 以只读方式打开模型空间的块表记录 Open the Block table record Model space for read
Dim acBlkTblRec As BlockTableRecord
acBlkTblRec = acTrans.GetObject(acBlkTbl(BlockTableRecord.ModelSpace), _
OpenMode.ForRead)
Dim acObjId As ObjectId
'' Step through each object in Model space
For Each acObjId In acBlkTblRec
Try
Dim acEnt As Entity
acEnt = acTrans.GetObject(acObjId, _
OpenMode.ForWrite)
acEnt.ColorIndex = 1
Catch
Application.ShowAlertDialog(acObjId.ObjectClass.DxfName & _
" is on a locked layer." & _
" The handle is: " & acObjId.Handle.ToString())
End Try
Next
acTrans.Commit()
End Using
End Sub