VBA と VB のエラー処理は、On Error ステートメントを使用して行います。VB.NET の場合、On Error ステートメントも問題なく使用できますが、Try ステートメントを代わりに使用することをお勧めします。Try ステートメントは On Error Resume Next ステートメント、On Error GoTo Label ステートメント、VBA、VB よりも柔軟です。
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 void ColorEntities()
{
// ' Get the current document and database, and start a transaction
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// ' Open the Block table record for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;
// ' Open the Block table record Model space for read
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;
// ' Step through each object in Model space
foreach (ObjectId acObjId in acBlkTblRec)
{
try
{
Entity acEnt;
acEnt = acTrans.GetObject(acObjId, OpenMode.ForWrite) as Entity;
acEnt.ColorIndex = 1;
}
catch
{
Application.ShowAlertDialog(acObjId.ObjectClass.DxfName + " is on a locked layer." + " The handle is: " + acObjId.Handle.ToString());
}
}
acTrans.Commit();
}
}
<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