Lesson 7 debugging and simple classes
This presentation is the property of its rightful owner.
Sponsored Links
1 / 47

Lesson 7 — Debugging and Simple Classes PowerPoint PPT Presentation


  • 44 Views
  • Uploaded on
  • Presentation posted in: General

Lesson 7 — Debugging and Simple Classes. Microsoft Visual Basic .NET, Introduction to Programming. Objectives. Use breakpoints and Watch windows to locate program errors. Use the Immediate window to check and change values.

Download Presentation

Lesson 7 — Debugging and Simple Classes

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Lesson 7 debugging and simple classes

Lesson 7 — Debugging and Simple Classes

Microsoft Visual Basic .NET, Introduction to Programming


Objectives

Objectives

  • Use breakpoints and Watch windows to locate program errors.

  • Use the Immediate window to check and change values.

  • Check a program's logic by stepping through the program one line at a time.

  • Use the Try-Catch-Finally statements to trap run‑time errors.

  • Write a simple class and use it in an application.


Vocabulary

Break mode

Breakpoint

Bugs

Err object

Error log (log file)

Error trapping

InterCap naming convention

Object Browser

Option Explicit On

Step Into

Syntax errors

Watch expression

Watch window

Widening conversion

Vocabulary


What s the problem

What's the Problem?

A program can fail in countless ways. The more complex the program, the more likely it is that hidden bugs are waiting to leap out and bite the unwary user. As a programmer, it is your job to keep the bugs at bay. If you carefully think out and test your applications, you can minimize errors. Despite careful planning, every programmer should anticipate that creative users will find ways to crash his or her programs.


Building communication skills

Building Communication Skills

It is no surprise that communication with the user is an important part of preventing bugs. Applications that prompt the user for input should present the user with sample data that illustrates what kind of input is acceptable. A prompt to the user to enter his or her last name requires minimal instructions. A prompt to enter a date or dollar amount is best presented with a pattern for the user to follow and error-trapping code to give further instructions to the user if he or she makes a mistake.

Error trapping means to reroute program flow during a run‑time error to code designed to handle the problem.


Intercap naming convention

InterCap Naming Convention

With the InterCap naming convention, you provide an initial capital letter for each part of the variable or control name. For example, a text box in which the user is to enter an unpaid balance might be named txtUnpaidBalance.

When you define a variable with the Dim (or Public) statement, you set a pattern of capitalization for the variable name that Visual Basic follows for the rest of the program. If you use the statement Dim FirstName As String, for example, to define the string variable FirstName, then every time you enter the name firstname, Visual Basic automatically capitalizes the "f" and the "n" so that the case of the characters of the name that’s entered matches the case of the characters of the name defined in the Dim statement.


Option explicit on and option strict

Option Explicit On and Option Strict

The Option Explicit On statement requires all variables to be declared before they are used. Option Explicit On is included in Option Strict.

Option Strict requires that all variables be declared before they are used and also prevents the value of a variable from being assigned to another variable if the assignment would result in data loss.


Syntax errors

Syntax Errors

Visual Basic checks each line of code for syntax errors as soon as you press the Enter key. Syntax errors, such as misspelling a command or omitting a statement, occur in the structure of the statement. For example, if you mistakenly enter Select End instead of End Select at the end of a Select Case statement, Visual Basic catches the error as soon as you press Enter or leave the line and prompts you for a correction.


Breakpoints

Breakpoints

A breakpoint is a spot in the code at which the program pauses while it is being executed. When program execution encounters a breakpoint and pauses, it is in break mode. With the program in break mode, you can examine and change values of variables. A program also enters break mode automatically when it encounters a run‑time error.

Once in break mode, you can single-step through the statements of the program code. Select Debug on the menu bar and then the Step Into command to single-step through the statements. In this mode, the statements are executed one at a time, allowing you to examine each statement.


The final appearance of the how many more payments form

The Final Appearance of the How Many More Payments? Form


Step by step 7 1

Step-by-Step 7.1

Dim Balance, Payment As Decimal, Rate As Double

Dim Count As Integer

balance = txtbalance.Text.ToDecimal

payment = txtpayment.Text.ToDecimal

rate = txtrate.Text.ToDouble

count = 0

do

count += 1

balance = balance + balance * CDec(rate) /12 – payment

loop until balance <= 0

lblpayments.Text = count.ToString


Step by step 7 11

Step-by-Step 7.1

txtUnpaid.ResetText

txtPayment.ResetText()

txtRate.ResetText()

lblPayments.ResetText()

txtUnpaid.Focus()


New breakpoint dialog box

New Breakpoint Dialog Box


Debug error message

Debug Error Message


Watch expression

Watch Expression

  • A watch expression is often just a single variable, but the watch expression can be any expression. For instance, you may want to watch the value of an algebraic expression like 180*Angle/Pi, where Angle is the radian measure of an angle and the watch expression represents the degree measure of the angle.

  • The value of a watch expression is displayed in the Watch window onlywhen the program enters break mode.

  • Single-stepping through the program while in break mode shows the values of the variables in the Watch window changing as each line is executed. Select the Step Into command on the Debug menu, or use the keyboard shortcut, F11, to start the process.


The quickwatch window

The QuickWatch Window


Lesson 7 debugging and simple classes

Note

Is the Watch window visible? If not, select Debug | Windows I Watch from the menu bar. If it is too small to read, use the mouse to enlarge it. It shows the status of each watch expression.


Breakpoint condition dialog box

Breakpoint Condition Dialog Box


The new breakpoint window showing the condition breakpoint

The New Breakpoint Window Showing the Condition Breakpoint


Programming skills

Programming Skills

The Step Into option steps into any procedure or function called in the code and executes it line by line. If you are certain there is no error in a particular procedure or function, execute the code by entering the keyboard shortcut Shift+F11, or select Debug I Step Over from the menu bar. With this command, the program will not show a line‑by‑line execution of a procedure or function called in the code. It executes the procedure or function without pause and returns to executing the lines of the calling procedure one at a time. The Step Out command (it’s keyboard shortcut is Ctrl+Shift+F11) finishes the execution of the current procedure or function and shifts program flow to the statement that follows the procedure. Use this option if you are sure the remaining code of a procedure or function is error‑free.


Programming skills1

Programming Skills

Part of the debugging process is to build a set of input data that tests all aspects of the program. Include test data that tests the boundary conditions of the program (if any exist), the largest or smallest possible values, negative values, etc.


Try catch finally statement

Try-Catch-Finally Statement

The syntax of the simplest version of the statement looks like this:

Try

one or more statements

Catch [When condition]

one or more statements

Finally

one or more statements

End Try


Step by step 7 3

Step-by-Step 7.3

Dim PathName As String = "c:\Notes\note.txt"

Dim f As File = New File(PathName)

Dim fs As StreamWriter

Dim strContent As String = txtContent.Text

fs = f.CreateText

fs.WriteLine(strContent)

fs.Close()


Step by step 7 31

Step-by-Step 7.3

Dim PathName As String = "c:\Notes\note.txt"

Dim f As File = New File(PathName)

Dim fs As StreamWriter

Dim strContent As String = txtNotes.Text

Try

fs = f.CreateText

fs.WriteLine(strContent)

fs.Close()

MessageBox.Show("File successfully created.")

Catch

MessageBox.Show("Unable to open the file.")

End Try


Historically speaking

Historically Speaking

In the first versions of BASIC, every line was numbered and every program was a maze of “Go To's” followed by statement numbers. It was possible to write code that was indecipherable even to the programmer. Also, the debugging capabilities of the language were far less sophisticated than they are today. The Tron command turned on Trace mode. In Trace mode, the line number of each line was listed as it was executed. The result was an unmanageable list of line numbers, which no one ever looked at.


Adding the when option

Adding the When Option

Try

z = x / y

Catch When x = 3

MessageBox.Show("raw value of three:" & x.tostring)

Catch When x = 4

MessageBox.Show("raw value of four:" & x.tostring

Catch

MessageBox.Show("anything else:" & x.tostring)

End Try


Step by step 7 4

Step-by-Step 7.4

Dim x, y As Integer, z As Decimal

x = 3 : z = CDec(x / y)

z = x \ y

x = CInt(InputBox("Enter a number:"))

Try

z = CDec(x / y)

Catch When x = 3

MessageBox.Show("raw value of three:" & x.ToString)

Catch When x = 4

MessageBox.Show("raw value of four:" & x. ToString)

Catch

MessageBox.Show("anything else:" & x. ToString)

End Try


A system generated error message

A System-Generated Error Message


Log files

Log Files

Often an error handler saves error data in a file called an error log or log file. The error log is a text file that lists errors and the time when they occur. It is often just a simple text file, not a complex database.


Step by step 7 5

Step-by-Step 7.5

' Move Try to the top

Try

' Change "My Directory" to "notes"

Dim PathName As String = "c:\notes\note.txt"

Dim f As File = New File(PathName)

Dim fs As StreamWriter

Dim strContent As String 'Remove "= txtNotes.Text"

fs = f.CreateText

fs.WriteLine(strContent)

fs.Close()

MessageBox.Show("File successfully created.")


Step by step 7 51

Step-by-Step 7.5

Catch

MessageBox.Show("Unable to open the file.")

' New addition to create and add to ErrorLog.txt

Dim CurrentDate As Date

Dim ErrorPath As String = "c:\My Documents\ErrorLog.txt"

Dim f2 As File = New File(ErrorPath)

Dim fs2 As StreamWriter

fs2 = f2.AppendText

fs2.WriteLine("Could not open the file:")

fs2.WriteLine(Err.Description & " " & Err.Number)

fs2.WriteLine(CurrentDate.Now.ToString)

fs2.Close()

End Try


Computer ethics

Computer Ethics

You wouldn't record a phone call without the caller's permission. It is unethical to create a log file of a user's personal data to be retrieved by the programmer at a later date. Since such a file could be created without the knowledge of the user, you must adhere to a strict self‑discipline of treating others as you would like to be treated.


Classes and objects

Classes and Objects

  • A class is a definition from which an object is created. You have been working with classes every time you write a program. Each program you write is a class definition of the application the user runs.

  • Use the keyword New in a declaration statement to create a new object.

  • For instance, the statement Dim f As File creates a variable f that can represent an object of the file type, but no new object is created. The statement Dim f As File = New File(PathName) declares a variable of the File data type and then initializes that variable to a new File object. An equivalent statement is Dim f As New File(PathName). The word New creates a new object of the given data type.


Step by step 7 6

Step-by-Step 7.6

Dim frmNewForm As New Form()

frmNewForm.Text = "New Form"

frmNewForm.show()

Dim frmNewForm As New Form1()


The add new item dialog box

The Add New Item Dialog Box


Step by step 7 7 clscreditcard vb

Step-by-Step 7.7 clsCreditCard.vb

Public Description As String

Public CreditLimit As Decimal

Public CurrentBalance As Decimal

Public InterestRate As Double


Final appearance of the addingaclass form

Final Appearance of the AddingAClass Form


Step by step 7 7

Step-by-Step 7.7

txtDescription.ResetText()

txtCreditLimit.ResetText()

txtCurrentBalance.ResetText()

txtInterestRate.ResetText()

txtDescription.Focus()

Dim CreditCard(10) As clsCreditCard

Dim Index As Integer = 0


Step by step 7 71

Step-by-Step 7.7

Dim Card As New clsCreditCard() ' creates a new card

With Card

.Description = txtDescription.Text

.CreditLimit = txtCreditLimit.Text.ToDecimal

.CurrentBalance = txtCurrentBalance.Text.ToDecimal

.InterestRate = txtInterestRate.Text.ToDouble

End With


Step by step 7 72

Step-by-Step 7.7

Try

CreditCard(Index) = Card ' put the card in the array

Index += 1 ' increment the Pointer

Catch

MessageBox.Show("The Array is full!")

End Try

btnClear_Click(sender, e) ' call the Clear routine


Step by step 7 73

Step-by-Step 7.7

lstDisplay.Items.Clear()

Dim Ind As Integer = 0

For Ind = 0 To Index - 1

With CreditCard(Ind)

lstDisplay.Items.Add(.Description & " " & .CurrentBalance.ToString)

End With

Next


Adding a method

Adding a Method

Adding a method to a class is as easy as creating a new event procedure.


Step by step 7 8

Step-by-Step 7.8

Function MonthlyInterest() As Decimal

MonthlyInterest = CDec(CurrentBalance * InterestRate / 1200)

End Function

Dim ItemNumber As Integer = lstDisplay.SelectedIndex

MessageBox.Show(CreditCard(ItemNumber).MonthlyInterest.ToString)


Summary

Summary

  • Program bugs are errors and flaws in programming code. Debugging is the process of finding and eliminating bugs.

  • Using the InterCap naming convention facilitates using the object or variable name in the debugging process. First define a variable in a declaration statement with capital letters at the beginning of each word. Then enter the variable names with all lowercase letters when writing code. If the proper letters are not converted to uppercase when the cursor leaves the line, the names have not been recognized by Visual Basic.

  • The Option Explicit On statement requires all variables to be declared before they are used. Option Explicit On is included in Option Strict. Option Strict requires that all variables be declared before they are used and also prevents the value of a variable from being assigned to another variable if the assignment would result in data loss.


Summary1

Summary

  • Syntax errors, errors in statement structure, are identified by Visual Basic when the cursor leaves the line of a flawed statement. A jagged underline highlights the part of the statement in error, and the ToolTip contains a description of the error.

  • A breakpoint stops program execution while the program is running. While the program is stopped, it is in break mode. When in break mode, the values of variables can be examined and changed in the Immediate window.

  • A watch expression lets you examine particular values automatically in the Watch window when the program enters break mode. A conditional watch expression can put the program in break mode when a particular condition is satisfied or when a variable changes value.


Summary2

Summary

  • The On Error Resume Next statement skips any line of code that causes a run-time error. On rare occasions, simply ignoring a line is a sufficient fix for a problem.

  • The Try-Catch-Finally statement is a versatile way to trap program errors and execute code that tries to repair the error or reports the error to the user.

  • The conditional Catch part of the Try statement lets the programmer differentiate between different conditions that may cause a run-time error. This lets the program tailor its response to the particular error.

  • Err and Error are system variables that contain the error number and description of the most recent error. The Err object also contains the error number and description, as well as the source of the error and additional information.


Summary3

Summary

  • An error log is a simple text file in which information about program errors is saved. The error number, description, and source, as well as the time the error occurred, are the kinds of information to save in the log file.

  • Classes are definitions from which objects are built. Visual Basic has a number of built-in classes to create things like text boxes and buttons. The New keyword is necessary to create a new object.

  • Variables declared in a class definition are the properties of the objects created with the class.

  • Functions and procedures defined in a class definition are the methods associated with the object created with the class.


  • Login