Try and Catch

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report
I have a very basic piece of code to understand how the try and catch works. I think I understand it somewhat but not entirely. Here is the code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.Geometry; using Autodesk.AutoCAD.Runtime; using AcAp = Autodesk.AutoCAD.ApplicationServices.Application; namespace AddCirc2 { public class Commands { [CommandMethod("AddCir")] public void Test() { var doc = AcAp.DocumentManager.MdiActiveDocument; var db = doc.Database; var ed = doc.Editor; using (var trans = db.TransactionManager.StartTransaction()) { BlockTable blkTbl = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead); BlockTableRecord blkTblRec = (BlockTableRecord)trans.GetObject(blkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite); try { Point3d cirCen = new Point3d(5, 5, 0); Circle cir = new Circle(cirCen, new Vector3d(0, 0, 1), 6.3); Line lin = new Line(cirCen, new Point3d(cir.Center.X + 6.3, cir.Center.Y, 0)); blkTblRec.AppendEntity(cir); blkTblRec.AppendEntity(cir); blkTblRec.AppendEntity(lin); trans.AddNewlyCreatedDBObject(cir, true); trans.AddNewlyCreatedDBObject(lin, true); trans.Commit(); } catch (System.Exception ex) { ed.WriteMessage("\nError: " + ex.Message); trans.Abort(); } } } } }
Questions:
1. If I call the trans in a using statement does it really matter if I have a try and catch block?
2. I saw in an example online that the trans.abort() was called in the catch block. I ignored it and also added it, both ways I do not see any difference. The error is still thrown.
3. The blkTbl and blkTblRec initialization is happening outside the try but inside the using. Why does it matter? can I initialize it even before the using statement is called, that is right after var ed = doc.Editor;
var ed = doc.Editor;
I am also trying to understand where does the try and catch blocks begin? In other words, why can I not have everything included in the try and catch. So try goes right at the top and the using statement is called in the try block and then have a catch block at the end. Is that acceptable?