470 likes | 493 Views
Learn to identify and fix syntax errors like missing parts of code structures and logical errors in code that may lead to unexpected results. Discover good coding practices to prevent errors. Comprehensive guide for programmers.
E N D
CIS 338: Debugging Dr. Ralph D. Westfall May, 2011 Change font back to Tahoma from AjaxSurrealFreak (see Come On, I Thought I Knew That! for rationale)
Error Handling/Debugging • syntax errors • logical errors • good coding practices to minimize errors • testing your code • debugging methods • "bullet proofing"
Syntax Errors • spelling or punctuation errors "select * where Sitty="Pomona" 'in SQL MsgBox "Hello" 'use MsgBox("Hello") • missing parts of control structures • For but no Next 'on tests • If but no End If ' " " • extra parts for control structures • extra End Sub at end
Syntax Errors - 2 • using a method as a property MsgBox = "Welcome" • don't use = with methods • using a property as a method • lblName.Caption("Name") • properties are values, so need to use =
Syntax Errors - 3 • writing to a "read only" property • changed values could destroy data or make it inaccessible • lstSpecialty.Items.Count() = 10 • not using New to create an object objPeople = Persons() 'should be objPeople = New Persons()
Syntax Errors - 4 • type mismatch • e.g. can't do arithmetic with text • 5 / "hello" MsgBox(5/txtName.Text) 'text or empty • or with an undefined value MsgBox(5/CInt(txtNameText))'missing dot • won't show as an error right away if not using Option Strict On)
Logical Errors • compiler usually) catches division by literal value of zero as a syntax error Dim z As Integer = 3 / 0 • division by a variable that becomes zero is much harder to spot Dim x as Integer = 3 Dim y as Integer = 3 y = x \ (x - y) 'integerdivision 'divide decimals by 0 = infinity
Logical Errors - 2 • code that doesn't do what you want it to do • example: trying to swap values of nA, nB • nA = nB 'destroys value of nA • nB = nA • 'nB gets own previous value back
Logical Errors - 3 • code that will never run (“dead code”) • example: comparison If nAge < 3 Then Print "less than 3" ElseIf nAge >= 3 Then Print "3 or older" ElseIf nAge >= 55 Then Print "55 or older" 'will never run End If
Logical Errors - 4 • changing value of the counter in a loop • students make this mistake often on tests • final exam tip: memorize loop syntax For i = 0 to 9 lstName.Item.Add(names(i)) i += 1 'NO!!!! Next
Good Coding Practices • indent code inside loops and conditionals • "pretty printing" • For nI = 1 to 2 • nJ = nI^2 'exponentiation • Next nI 'show (optional) counter • use comments • but only where they are needed
Good Coding Practices - 2 • use Option Strict at start of code for forms and other modules • forces you to declare all variables • helps spot spelling mistakes • stops implicit data type conversions • should you use Option Strict when the code goes into "production?" • why or why not? • turn off debugging when ASP goes live
Good Coding Practices - 3 • consistent objectnaming convention • frmDataEntry 'a Windows form • lstName 'a ListBox • VB capitalizes function names for you • e.g. string function names • sName.ToUpper() 'to Upper Case • sAddress.TrimStart() • 'removes left side spaces
Good Coding Practices - 4 • type checking: is data what you expect? • If IsNumeric(txtQuantity.Text) Then • nTot = nTot + CInt(txtQuantity.Text) • End If • 'can check IsDBNull( ) in databases • type conversion: change data so it is usable • nValue = CInt(dItem1 + dItem2) • 'convert to Integer
Good Coding Practices - 5 • use subprocedures, functions, queries • for anything more than 3-5 lines of same or similar code in more than one place • advantages: • shorter programs • easier to debug and maintain • may be able to reuse them elsewhere
VB.NET Debug Settings • Tools>Options>Projects>VB Defaults or project>Properties> Compile • Option Explicit On requires that all variables be declared • Option Strict On prevents implicit conversions e.g., • from a String to a numeric data type • from a larger numeric type to a "narrower" type e.g., Double to Integer
VB.NET Debug Settings -2 • Tools>Options>Text Editor>Basic • Auto list members shows/inserts object properties and procedures • can help avoid typing errors • Parameter information – shows function parameters (order, data type) • Options>Text Editor>Basic>VB Specific • Pretty listing (reformatting) code indents next line the same as previous one
After You Code Project • must be tested • alpha testing – in house • beta testing – outside users • how much (%) of budget for testing? • depends on intended use of project and consequences of a failure • minor inconvenience vs. someone dies
Regression Testing • maintenance accounts for up to 80% of system costs, so it's important to test for errors in code that used to work but has been modified • this is called "regression testing" • testing to see if the system has "gone backwards" from working as it should
Alpha Testing Approaches • manual • automated testing software • TestComplete • QA Wizard Pro 2009
Manually Test Your Code • test the different ways a user could go through the application • data entry example: Add, Change, Delete and navigation buttons • what happens if click a button when no data shows? • what happens if do something twice e.g., Delete, then Delete again without moving to different record?
Testing Your Code - 2 • test possible data values • example: zip codes • boundary values (included or not?) • 00000 and 99999 • values in between boundaries • 00001 to 99998 (random samples) • out-of-bounds values • negative #s? 4 or 6 digit #s? • text #s? ("three" has 5 characters!)
Exercise: Create Test Plan • data entry form • 4 TextBoxes • Add, Edit, and Delete buttons • 4 Navigation buttons (First, etc.) • write down list of steps that you think would be adequate to test this form • indicate reasons for each test • identify things that could go wrong
Debugging Statements • "trace" statements can help determine values before place where problem is MsgBox(sSQL) 'view SQL string • files with no user interface could use Console.Writeline instead to show values • if use Autos Window, can see variable values when crashes occur • discussed in later slides
Debugging Class Modules • create another VB project to just provide inputs to module and get outputs from it • set up code ("driver") in a form to call class module's procedure(s) with possible test values • similar to how you would test classes in Java
Other VB.NET Debugging • as you write code, real time error checking spots syntax errors • if running and execution is halted at a "break," can see data values in current procedure by moving mouse pointer over variable names • good tutorial on commonly used debugging capabilities
VB Debugging Environment • debug menu items • Debug toolbar has some of same items • breakpoints toggle on and off • click on editor's left border to stop (break) where want to start running line by line • e.g., call to DemoStep( )in notes • can also Clear All Breakpoints with a selection on menu
VB Debug Capabilities - 2 • running code one line at a time from breakpoint with Step icons • Step Over – only steps into lines in this procedure (doesn't step in called ones) • Step Into – also runs lines one by one in called procedures • Step Out - finishes current procedure or block, then stops on line after it started
Debugging Example • set a breakpoint in some VB code • e.g., in a loop or at a subroutine call • run program • use different step keys • to view path through code • view changes in values in when mouse goes over a variable in code that has already ran
Debugging Example - 2 • run program • open Debug>Windows>Locals • can expand items by clicking + • use different step keys • view changes in values in Locals window as step through code
Run to Cursor • click in code at statement to run to • right-click:>Run to Cursor, then Start the project • or can click/drag yellow arrow on Breakpoint to line to execute next, then click on Step Into icon • can skip executing lines with this • note "tool tip" when mouse over arrow
Other Debug Windows • while running, can use following • right-click variable> Add Watch – shows values for variables you identify • Debug>Windows>Locals (slide 30) • Debug>Windows>Autos – like Locals, but limited to current line and up to three lines before/after it (7 lines)
Debug Windows Example • open Debug>Windows>Immediate while code is running • can change the value of a variable • assign a value, calculate a new value, run a MsgBox, etc. • view effect in Locals window • type in a line of executable code e.g.,[declared variable] += 1
Debug Windows Example - 2 • open a code window and Start program • highlight and right-click variable name • Add Watch • Step Into, view changes in Watch window • how is a Watch removed? • right click variable in Watch window>Delete Watch
Debug Windows Example - 3 • Debug>Windows>Call Stack • can click when program is running • shows current subroutine, routine that called it, routine that called the previous routine, etc. 'see Notes • indicates place where each called from • Clear All Breakpoints on Debug menu • don't have to remember where you set individual breakpoints
"Bullet Proofing" Code • prevent all possible errors from happening • make it impossible for user to enter bad data or to trigger an invalid action • include code in project that will "trap" errors that can't be prevented and take appropriate corrective action
Controlling Program Use • example: state abbreviations • all have 2 characters e.g., CA, OR, WA • 3 characters could crash database • only around 50 valid combinations (states) • possible "design-time" solutions: • set TextBox MaxLength property = 2 • use a drop-down ListBox or ComboBox instead so user can't enter bad values
Controlling Program Use - 2 • example: key field in a database should not be changed or input because database creates key value • property TextBox.Enabled = False shows data but user can't do anything with it • property TextBox.ReadOnly = True shows data, allows user to copy (but not change) it
Controlling Program Use - 3 • can use code to prevent inappropriate events • example: repeating some buttons used to cause a crash e.g., Delete, Delete • when the first button is clicked, have code set btn[name].Enabled = False for the button that causes the crash • need to enable the button again (after user moves away from the deleted record) 'notes
Validating/Validated Events • code can prevent bad inputs into TextBoxes • Validating – when control loses Focus • for preventing bad inputs • Validated - after Validating has occurred • can use Validated to trigger different actions based on different input values, after bad inputs have been prevented
Validating Example Private Sub TextBox1_Validating(etc. 'runs when textbox loses focus '.Text property initially set to: "me" MsgBox("TextBox1 is validating") If TextBox1.Text <> "Me" Then MsgBox("Don't try to change Me!!!") TextBox1.Focus() 'returns to it e.Cancel = True 'event not Validated End If End Sub 'or can use regular expression conditions
Validated Example Private Sub TextBox1_Validated(etc. MsgBox("TextBox1 has been validated") MsgBox("Thanks 4 leaving Me alone :-)") End Sub
Exception Handling • catch (trap) exceptions (errors) before they crash the program, and then: • end the program with all normal clean up • or keep running but avoid code related to the error (limited functionality) • or give a message to user to fix problem • e.g., put a CD in the E:\ drive
Try … Catch • Try block "traps" exceptions • more efficient than writing subroutines to handle the same types of problems • Try block redirects ("throws") flow to Catch block(s) below, where programmer's code handles problem(s) • can also have a Finally block to deal with exceptions not handled in individual Catch block(s)
Types of Exceptions • VB.NET has Exception classes that handle specific types of errors • Exception classes can have more specific subclasses • ArithmeticException 'general • DivideByZeroException 'more specific • ArgumentException • ArgumentNullException
Exception Handling Structure Try [code that could cause a crash] [Catch [object] as [type of]Exception ] [code for general [or specific] problem] 'there can be 0, 1 or several Catch blocks [Finally] (optional) [catch other exceptions, or do something else e.g., Dispose of object resources] End Try
Exception Handling Example Option Strict On Private Sub etc. Dim intZ As Integer = 33 Try Dim intA As Integer = 3 intZ = 5 \ (intA - 3) 'integer division Catch ex As ArithmeticException MsgBox("Error: " & ex.ToString()) Finally 'not needed here, just for example MsgBox(CStr(intZ)) 'still original value End Try