Dealing with Errors in AutoCAD Programs

29 Oct, 2015 By: Andrew G. Roe

Errors are bound to happen, but it’s simple to incorporate error handling in your VB.NET and VBA code.


Let’s briefly review the code to understand how this works. The On Error statement is included at the beginning of the program to tell VBA what to do if an error occurs. In this case, the statement directs the program to jump to another code segment called ErrorHandler. The Dim statements declare variables for double-precision numbers Var1 and Var2, the two input variables, and Pct, the output value. The InputBox function is used to prompt the user for the two input variables. A simple math expression calculates the value of Pct, and a message box displays the result.

If the user enters invalid parameters, the error-handling code displays different messages, depending on the error type. VBA distinguishes various run-time errors by number, such as Error 11 when dividing by zero, and Error 13 when the data entered does not match the variable type. Within the ErrorHandler code, a Select Case structure executes different statements depending on which error is encountered.

You can save your program by clicking File > Save in the VBA IDE. You can then access it later in several different ways, such as by manually loading it in future AutoCAD sessions or embedding it in the current drawing.


The .NET environment offers similar error-handling tools, but also offers a different approach called the Try...Catch block. This example uses Visual Basic.NET, although you can also use Visual C#.NET. To complete this exercise, you’ll need either Visual Studio.NET or the free Visual Studio Express.

1. Start Visual Studio and create a new project by clicking File > New > Project.

2. In the New Project dialog box, select Windows Forms Application, then type a name and file location. Click OK to close the New Project dialog box.

3. Click on the Form1.vb[Design] tab to display the form. From the Toolbox, click and drag a button onto the form.

4. Click View > Properties Window. In the Properties window, change the Text property of the button to “Calculate.”

5. Double-click the button to display the Code window. A subroutine is already set up for the command button you just double-clicked. Modify the code to read as follows:

   Public Class Form1
      Private Sub Button1_Click(sender As System.Object, _
      e As System.EventArgs) Handles Button1.Click
         Dim Var1 As Integer
         Dim Var2 As Integer
         Dim Pct As Double
            Var1 = InputBox("Enter a numerator: ")
            Var2 = InputBox("Enter a denominator: ")
            Pct = Var1 \ Var2
            Pct = Var1 / Var2
            MsgBox("Percentage = " & Pct)
         Catch Ex As Exception
            MessageBox.Show("Reached end of program.")
         End Try
      End Sub
   End Class

6. With AutoCAD running, click the Play button (or press F5) to build and run the application.

7. Click the Calculate button to display the prompts for two values.

8. Enter various combinations, including a 0 for the denominator, to generate error messages. 

9. Click OK to close the information window, then click the X in the upper right of the UserForm to stop execution of the program and close the UserForm.

As you can see, the .NET program differs from the VBA program in several ways, but also has some common features. Dim statements are again used to declare variables. In this case, Var1 and Var2 are declared as integers due to a minor difference in how VB.NET handles dividing by zero. (More on that shortly.) Pct is again declared as a double-precision variable.

The Try portion of the Try...Catch block contains the code to be executed if the user enters valid input variables. As with VBA, the InputBox function prompts the user for input variables. The Pct value is calculated two different ways to demonstrate a unique feature in VB.NET. Integer division is carried out using the \ operator. If the denominator is zero, an exception is thrown and the Catch code executes. If a valid denominator is entered, the \ operator returns an integer (rounded down to the nearest whole number). Because this is not usually the desired format for a percentage, the Pct value is recalculated using the / operator, which performs floating-point division. The final answer is displayed in a message box.

If only a floating-point calculation is performed, VB.NET will allow division by zero and display an answer of infinity. As an alternative, you can capture an infinity exception in VB.NET, but that is beyond the scope of this article. You can experiment with various situations by commenting out one of the Pct calculation statements, using the apostrophe (‘) at the beginning of the line.

If the user enters invalid parameters, such as a zero for a denominator, the program jumps to the Catch portion and displays an error message, more accurately called an exception message in .NET. The Finally portion executes whether or not the exception occurs.

You can save your .NET application by clicking File > Save All to save the code, the form, and the other elements of the project.

As you can see, there are various ways to handle errors, depending on the programming environment. Try to include some kind of error handling in your programs to minimize the frustrations of end users and improve your program efficiency.

1 2 

Add comment

Note: Comments are moderated and will appear live after approval by the site moderator.


Re: Dealing with Errors in AutoCAD Programs
by: rexxitall
October 31, 2015 - 10:16am
Ther is something more to say. Not all errors has to be "handled" - especially not if you are in coding process. A error handler or prevent error handler is also often a case for GOTO. A few right placed gotos saves endless if then structures. Some sample code below. Small dirty but efficiant :) And for sure just as a sample. function dosomething as boolean dosomething =false txt=inputbox("test") if txt="" goto raus 'prevent error exit on error resume next 'we ignore errors a while err.clear 'clean error state k=val(txt) l=1/k .. ... .... 'so if somewhere a error ocurs we are out ' and function will be false :) if err.number <>0 then goto raus err.clear on error goto 1 'switch error on again use 'standard error handler of VBA ... ... on error goto errorhandler .... 'tail of function no further real processing dosomething=true will only be true if everythig went right errhandler: 'anoy and frustrate the user ;) call errorhandler("dosomething", err) raus: 'german word for exit ' i use this often just to exit a function on user abort yu may also use err.raise to create a fake error just for this purpose end sub Sub errorhandler(byval err,function_name as string ) put the rrorhandler somewhere as a function msgbox function_name & " " & err.description end sub

Download Cadalyst Magazine Special Edition