Author Topic: Try Catch Finally Block Exception Error  (Read 1649 times)

0 Members and 1 Guest are viewing this topic.

sovby

  • Guest
Try Catch Finally Block Exception Error
« on: April 30, 2016, 10:01:48 PM »
I've been working on a tutorial that told me to add a try catch finally block. The catch(Exception ex) under the Lab 3 section just after instruction #8 is giving me an error that says 'Exception' is an ambiguous reference between 'System.Exception' and 'Autodesk.AutoCAD.Runtime.Exception'. It appears to be confused as to which exception to use but how do i go about fixing this? Here is my code:

// (C) Copyright 2016 by Microsoft
//
using System;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;


// This line is not mandatory, but improves loading performances
[assembly: CommandClass(typeof(Lab2.MyCommands))]

namespace Lab2
{

    // This class is instantiated by AutoCAD for each document when
    // a command is called by the user the first time in the context
    // of a given document. In other words, non static data in this class
    // is implicitly per-document!
    public class MyCommands
    {
        // The CommandMethod attribute can be applied to any public  member
        // function of any public class.
        // The function should take no arguments and return nothing.
        // If the method is an intance member then the enclosing class is
        // intantiated for each document. If the member is a static member then
        // the enclosing class is NOT intantiated.
        //
        // NOTE: CommandMethod has overloads where you can provide helpid and
        // context menu.

        // Modal Command with localized name
        [CommandMethod("MyGroup", "MyCommand", "MyCommandLocal", CommandFlags.Modal)]
        public void MyCommand() // This method can have any name
        {
            // Put your command code here
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor ed;
            if (doc != null)
            {
                ed = doc.Editor;
                ed.WriteMessage("Hello, this is your first command.");

            }
        }

        // Modal Command with pickfirst selection
        [CommandMethod("MyGroup", "MyPickFirst", "MyPickFirstLocal", CommandFlags.Modal | CommandFlags.UsePickSet)]
        public void MyPickFirst() // This method can have any name
        {
            PromptSelectionResult result = Application.DocumentManager.MdiActiveDocument.Editor.GetSelection();
            if (result.Status == PromptStatus.OK)
            {
                // There are selected entities
                // Put your command using pickfirst set code here
            }
            else
            {
                // There are no selected entities
                // Put your command code here
            }
        }

        // Application Session Command with localized name
        [CommandMethod("MyGroup", "MySessionCmd", "MySessionCmdLocal", CommandFlags.Modal | CommandFlags.Session)]
        public void MySessionCmd() // This method can have any name
        {
            // Put your command code here
        }

        // Start of Lab2
        // 1. Add a command named addAnEnt. Use the CommandMethod attribute and a
        // Public void function.
        // Note: put the closing curley brace after step 21.
        [CommandMethod("addAnEnt")]
        public void AddAnEnt()
        {

         // 2. Declare an Editor variable named ed. Instantiate it using the Editor property
        // of the Application.DocumentManager.MdiActiveDocument.Editor
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

        // 3. Declare a PromptKeywordOptions variable and instantiate it by creating
        // a new PromptKeywordOptions. Use a string similar to the following for the
        // messageAndKeywords string.
        // "Which entity do you want to create? [Circle/Block] : ", "Circle Block"
            PromptKeywordOptions getWhichEntityOptions = new PromptKeywordOptions("Which entity do you want to create? [Circle/Block] : ", "Circle Block");

        // 4. Declare a PromptResult. Use the GetKeywords method of the Editor variable
        // created in step 1. Pass in the PromptKeywordOptions created in step 2. Instantiate
        // the PromptResult by making it equal to the return value of the GetKeywords method.
            PromptResult getWhichEntityResult = ed.GetKeywords(getWhichEntityOptions);

        // 5. Add an if statement that tests the Status of the PromptResult created in step 4.
        // Use the PromptStatus enum for the test. (see if it is equal to PromptStatus.OK)
        // Note: Move the closing curly brace after step 21.
        // (After the following instructions)
            if (getWhichEntityResult.Status == PromptStatus.OK)
            {

        // 6. PromptStatus was ok. Now use a switch statement. For the switch argument
        // use the StringResult property of the PromptResult variable used above
        // Note: Move the closing curly brace after step 21.
        // (Above the closing curly brace for the if statement in step 5)
        switch (getWhichEntityResult.StringResult)
        {


        // 7. Use "Circle" for the case. (if the StringResult is "Circle") Below
        // we will use "Block" for the case. (jump ahead to step 15 to add the break
        // to resolve the "Control cannot fall through... message")
            case "Circle":

        // 8. We want to ask the user for the center of the circle. Declare
        // a PromptPointOptions variable and instatiate it by making it equal
        // to a new PromptPointOptions. Use "Pick Center Point : " for message parameter
                PromptPointOptions getPointOptions = new PromptPointOptions("Pick Center Point : ");

        // 9. Declare a PromptPointResult variable. Use the GetPoint method of
        // the Editor created in step 2. (Pass in the PromptPointOptions created
        // in step 8). Instantiate the PromptPointResult by making it equal to the
        // return of the GetPoint method.
                PromptPointResult getPointResult = ed.GetPoint(getPointOptions);

        // 10. Add an if statement that tests the Status of the PromptPointResult
        // created in step 9. Use the PromptStatus enum for the test. (make sure it is OK)
        // Note: Move the closing curly brace right before step 15.
        if ((getPointResult.Status == PromptStatus.OK))
        {

        // Begining of Lab3. Create the Circle or Block and BlockReference
        // 1. Declare a Database variable and instantiate it
        // using the Document.Database property of the editor created above. (ed)
        // Note: Add the Autodesk.AutoCAD.DatabaseServices; namespace for Database
        // and Transaction, use the using keyword (above the class declaration)
            Database dwg = ed.Document.Database;

        // 2. Declare a Transaction variable; instantiate it using the
        // TransactionManager.StartTransaction method of the Databse
        // created in step 1.
            Transaction trans = dwg.TransactionManager.StartTransaction();

        // 3. Add a try, catch and finally block. Move the try closing curly
        // brace right after step 8. Put the catch statement after this.
        // Enclose  step 9 in the catch call. Enclose step 10 in the finally call.
        // (Build the project and fix any problems).
            try
            {


        // 4. Declare a Circle variable and create it using the new keyword.
        // Use the the Value property of the PromptPointResult created in
        // Lab2 for the first parameter. For the second parameter (normal) use
        // Vector3d.ZAxis. Use the Value property of the PromptDoubleResult
        // (created in Lab2) for the radius.
        // Note: Need to add Autodesk.AutoCAD.Geometry; namespace for Vector3d.

        // 5. Declare a BlockTableRecord variable. Instatiate it using the
        // GetObject method of the Transaction variable created in step 2.
        // Use the CurrentSpaceId property of the Database variable created in
        // step 1 for the first parameter. (ObjectId) For the second parameter
        // use OpenMode.ForWrite. We are adding the circle to either ModelSpace
        // or PaperSpace. (the CurrentSpaceId determines this)

        // 6. Add the Circle to the BlockTableRecord created in step 5. Use the
        // AppendEntity method and pass in the circle created in step 4.

        // 7. Tell the transaction about the new circle so that it can autoclose
        // it. Use the AddNewlyCreatedDBObject method. The first argument is the
        // circle. Use True for the second argument.

        // 8. Commit the transaction by calling the Commit method. If the code gets
        // this far everything should have worked correctly.
            }
            catch (Exception ex)
            {


        // 9. Declare an Exception variable for the Catch.
        // (add "(Exception ex)" to the catch keyword)
        // Use the WriteMessage of the Editor variable (ed) created in Lab2.
        // Use "problem due to " + ex.Message for the Message parameter.
        // If an error occurs the details of the problem will be printed
        // on the AutoCAD command line.
            }
            finally
            {

           

        // 10. Dispose the transaction by calling the Dispose method
        // of the Transaction created in step 2. This will be called
        //whether an error on not occurred.

            }
       
        // 11. Now we want to ask the user for the radius of the circle. Declare
        // a PromptDistanceOptions variable. Instatiate it by making it equal
        // to a new PromptDistanceOptions. Use "Pick Radius : " for the message parameter.
            PromptDistanceOptions getRadiusOptions = new PromptDistanceOptions("Pick Radius : ");

        // 12. We want to use the point selected in step 9 as the
        // base point for the GetDistance call coming up. To do this use
        // the BasePoint property of the PromptDistanceOptions variable created
        // in the previous step. Make the BasePoint equal to the Value property
        // of the PromptPointResult created in step 9.
            getRadiusOptions.BasePoint = getPointResult.Value;

        // 13. We need to tell the input mechanism to actually use the basepoint.
        // Do this by setting the UseBasePoint property of the
        // PromptDistanceOptions created in step 11 to True.
            getRadiusOptions.UseBasePoint = true;

        // 14. Get the radius for the circle. Declare a PromptDoubleResult variable.
        // Instantiate it using the GetDistance method of the Editor variable created
        // in step 2. Pass in the PromptDistanceOptions created in step 11 and
        // modified in the previous steps.
            PromptDoubleResult getRadiusResult = ed.GetDistance(getRadiusOptions);
        }
        // 15. Add break to mark the end of the code for the "Circle" case.
        break;
        // 16. Add the Case for the "Block" (jump ahead to step 20 to add the break
        // to resolve the "Control cannot fall through... message")
            case "Block":

        // 17. Now we want to ask the user for the name of the block. Delcare
        // a PromptStringOptions varable and instatiate it by creating a new
        // PromptStringOptions. Use "Enter name of the Block to create : " for
        // the message parameter.
        PromptStringOptions blockNameOptions = new PromptStringOptions("Enter name of the Block to create : ");

        // 18. No spaces are allowed in a blockname so disable it. Do this by setting
        // the AllowSpaces property of the PromptStringOptions created in step 15
        // to false.
        blockNameOptions.AllowSpaces = false;

        // 19. Get the name the user entered. Declare a PromptResult variable
        // and instantiate it using the GetString method of the Editor object
        // created in step 2. Pass in the PromptStringOptions created in step 17.
        PromptResult blockNameResult = ed.GetString(blockNameOptions);

        // 20. Add break to mark the end of the code for the "Block" case.
        break;

        // 21. Build the project. Place a break point. Use the NETLOAD command
        // and run the AddAnEnt command. Step through the code and fix any errors.
        // Remember to run the command and test the code for both circle and block.
        // End of Lab2
            }
            }
        }
        // LispFunction is similar to CommandMethod but it creates a lisp
        // callable function. Many return types are supported not just string
        // or integer.
        [LispFunction("MyLispFunction", "MyLispFunctionLocal")]
        public int MyLispFunction(ResultBuffer args) // This method can have any name
        {
            // Put your command code here

            // Return a value to the AutoCAD Lisp Interpreter
            return 1;
        }

    }

}

kdub_nz

  • Mesozoic keyThumper
  • SuperMod
  • Water Moccasin
  • Posts: 2124
  • class keyThumper<T>:ILazy<T>
Re: Try Catch Finally Block Exception Error
« Reply #1 on: April 30, 2016, 10:18:25 PM »
I use Autodesk.AutoCAD.Runtime.Exception

http://help.autodesk.com/view/ACD/2016/ENU/?guid=GUID-A8D1137E-9283-4F1D-9B3E-89B90E5AA5A6

You may have the same issue with Application at times

I use this assignment
using AcApp = Autodesk.AutoCAD.ApplicationServices.Application;
and use AcApp in my code to to avoid confusion.

Good luck in your adventure :)
« Last Edit: April 30, 2016, 10:21:36 PM by kdub »
Called Kerry in my other life
Retired; but they dragged me back in !

I live at UTC + 13.00

---
some people complain about loading the dishwasher.
Sometimes the question is more important than the answer.

gile

  • Gator
  • Posts: 2507
  • Marseille, France
Re: Try Catch Finally Block Exception Error
« Reply #2 on: May 01, 2016, 01:57:46 AM »
Hi,

Autodesk.AutoCAD.Runtime.Exception (as all .NET exception types) derives from System.Exception.
So, using System.Exception will catch both specific AutoCAD exceptions and non-specific ones.
But a better practice is to use several catch blocks so that you can notify the end user (or developper) which kind of exception was thrown (see this topic).

Code - C#: [Select]
  1. // AutoCAD specific:
  2. catch (Autodesk.AutoCAD.Runtime.Exception e)
  3. {
  4.     ed.WriteMessage("\nAutoCAD error: " + e.Message);
  5. }
  6. // Non-specific:
  7. catch (SystemException e)
  8. {
  9.     ed.WriteMessage("\nSystem error: " + e.Message);
  10. }
Speaking English as a French Frog

gile

  • Gator
  • Posts: 2507
  • Marseille, France
Re: Try Catch Finally Block Exception Error
« Reply #3 on: May 01, 2016, 02:17:27 AM »
From this topic.

Quote
When an exception occurs in a try block, the system searches the associated catch blocks in the order they appear in application code, until it locates a catch block that handles the exception. A catch block handles an exception of type T if the type filter of the catch block specifies T or any type that T derives from. The system stops searching after it finds the first catch block that handles the exception. For this reason, in application code, a catch block that handles a type must be specified before a catch block that handles its base types, as demonstrated in the example that follows this section. A catch block that handles System.Exception is specified last.
Speaking English as a French Frog

sovby

  • Guest
Re: Try Catch Finally Block Exception Error
« Reply #4 on: May 01, 2016, 11:57:59 AM »
Hi,

Autodesk.AutoCAD.Runtime.Exception (as all .NET exception types) derives from System.Exception.
So, using System.Exception will catch both specific AutoCAD exceptions and non-specific ones.
But a better practice is to use several catch blocks so that you can notify the end user (or developper) which kind of exception was thrown (see this topic).

Code - C#: [Select]
  1. // AutoCAD specific:
  2. catch (Autodesk.AutoCAD.Runtime.Exception e)
  3. {
  4.     ed.WriteMessage("\nAutoCAD error: " + e.Message);
  5. }
  6. // Non-specific:
  7. catch (SystemException e)
  8. {
  9.     ed.WriteMessage("\nSystem error: " + e.Message);
  10. }
Thanks Gile. I figured it was a matter of it being confused as to which exception was being called if that's the right terminology.