Trapping Errors and Debugging Code. Programming errors can vary by … Type Cause Effect Severity Other factors Error types Include Syntax Logic Compile.

Slides:



Advertisements
Similar presentations
COMPUTER PROGRAMMING I Essential Standard 5.02 Understand Breakpoint, Watch Window, and Try And Catch to Find Errors.
Advertisements

AE6382 VBA - Excel l VBA is Visual Basic for Applications l The goal is to demonstrate how VBA can be used to leverage the power of Excel u VBA syntax.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Tutorial 12: Enhancing Excel with Visual Basic for Applications
The Web Warrior Guide to Web Design Technologies
Programming in Visual Basic
Microsoft VB 2005: Reloaded, Advanced Chapter 5 Input Validation, Error Handling, and Exception Handling.
Debugging Techniques1. 2 Introduction Bugs How to debug Using of debugger provided by the IDE Exception Handling Techniques.
Error Trapping Part II Runtime Errors Error Handling Conclusion Questions Syntax Errors Error Categories Logic Errors Debugging Tools The Err Object Error.
Lecture Roger Sutton CO331 Visual programming 15: Debugging 1.
VBA Modules, Functions, Variables, and Constants
Control Statements Making Decision in Your Program.
The IDE (Integrated Development Environment) provides a DEBUGGER for locating and correcting errors in program logic (logic errors not syntax errors) The.
If You Missed Last Week Go to Click on Syllabus, review lecture 01 notes, course schedule Contact your TA ( on website) Schedule.
1 Chapter 4 The Fundamentals of VBA, Macros, and Command Bars.
Input Validation Check the values entered into a text box before beginning any calculations Validation is a form of ‘self-protection’, rejecting bad data.
How to Debug VB .NET Code.
Chapter 2: The Visual Studio.NET Development Environment Visual Basic.NET Programming: From Problem Analysis to Program Design.
Guide To UNIX Using Linux Third Edition
5.05 Apply Looping Structures
© 1999, by Que Education and Training, Chapter 5, pages of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach.
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
Using the Select Case Statement and the MsgBox Function (Unit 8)
Saeed Ghanbartehrani Summer 2015 Lecture Notes #4: Working with Variables and User Interfaces IE 212: Computational Methods for Industrial Engineering.
1 Chapter 9 Writing, Testing, and Debugging Access Applications.
Enhancing User Interaction Through Programming
Introduction to Visual Basic. Quick Links Windows Application Programming Event-Driven Application Becoming familiar with VB Control Objects Saving and.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
Copyright © 2008 Pearson Prentice Hall. All rights reserved. 1 Microsoft Office Excel Copyright © 2008 Pearson Prentice Hall. All rights reserved
Tutorial 111 The Visual Studio.NET Environment The major differences between Visual Basic 6.0 and Visual Basic.NET are the latter’s support for true object-oriented.
Microsoft Visual Basic 2005 CHAPTER 4 Variables and Arithmetic Operations.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
ME 142 Engineering Computation I Debugging Techniques.
Visual Basic.NET BASICS Lesson 5 Exponentiation, Order of Operations, and Error Handling.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
MS Visual Basic Applications Walter Milner. Event-driven programming Standard approach for GUIs Contrast with old character interfaces – program determines.
Tutorial 51 Programming Structures Sequence - program instructions are processed, one after another, in the order in which they appear in the program Selection.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 8 Debugging, Creating Executable Files, and Distributing a Windows Application.
Applications Development
JavaScript, Fourth Edition
Two Forms Please use speaker notes for additional information!
GUI development with Matlab: GUI Front Panel Components GUI development with Matlab: Other GUI Components 1 Other GUI components In this section, we will.
1 Debugging and Syntax Errors in C++. 2 Debugging – a process of finding and fixing bugs (errors or mistakes) in a computer program.
1 Scripting Languages VBScript - Recognized mainly by Internet Explorer only - Netscape does have a plug-in JavaScript - Recognized by Internet Explorer.
Chapter-1 Introduction to Visual Basic GUI- A GUI is a graphical (rather than purely textual) user interface to a computer. The term came into existence.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
INSERT BOOK COVER 1Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall. Exploring Getting Started with VBA for Microsoft Office 2010 by.
Controlling Program Flow with Decision Structures.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
AVCE ICT – Unit 7 - Programming Session 12 - Debugging.
CIS 338: VB Variables Dr. Ralph D. Westfall April, 2011.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are used in programs so that values can be represented with.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration statement. For example: Dim.
Lecture 6 – Working with VBA Sub Procedures Dr Joanna Wyrobek 1.
Chapter 2: The Visual Studio.NET Development Environment Visual Basic.NET Programming: From Problem Analysis to Program Design.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
A variable is a name for a value stored in memory.
Chapter 2: The Visual Studio .NET Development Environment
Programming in visual basic .net Visual Basic Building Blocks
VBA - Excel VBA is Visual Basic for Applications
VBA - Excel VBA is Visual Basic for Applications
Microsoft Access Illustrated
Excel VBA Day 3 of 3 Tom Vorves.
Variables and Arithmetic Operations
Topics Introduction to File Input and Output
Tonga Institute of Higher Education
Topics Introduction to File Input and Output
Presentation transcript:

Trapping Errors and Debugging Code

Programming errors can vary by … Type Cause Effect Severity Other factors Error types Include Syntax Logic Compile Run-time Semantic

Trapping Errors and Debugging Code Syntax Errors Easy to avoid Sometimes Difficult to find MySpecialVariable MySpecialVaraible Adding Option Explicit to the beginning of Modules Forms ….can eliminate most of these types of errors Why?

Trapping Errors and Debugging Code Syntax Errors Use the IDE balloon help To Provide context sensitive help If one does not appear……. When typing a function name Indicates a problem You can look at code for hours and not see them Syntax Errors can produce logic errors Your program may not complain about a new variable that you intended to be a declared variable ….. with a slightly different name. Your indented variable may not get updated

Trapping Errors and Debugging Code Logic Errors Your code produces incorrect results VBA compiler may not complain but the results may cause Quirky results Incorrect results Run-time errors ( infinite loop ) Compile Errors VBA compiler is actually a syntax checker VBA compiler does not produce a free standing module or executable The compiler runs constantly and looks for errors If –then statement without an end if produces an error immediately

Trapping Errors and Debugging Code Compiler Errors Compiler checks Syntax Missing elements Punctuation Errors (missing periods commas etc.) Adding Option explicit will find data type mismatches at run time Dim num As Integer num = “string” Is allowed until runtime Error: Run time error 13 type mismatch

Trapping Errors and Debugging Code Run time errors Happens when something outside your program is incorrect. A disk access request can fail You could type the wrong information Will Cause your program to crash Divide by zero File not found Cannot be fixed by altering the logic of the program The program may require error handling routines Code Procedures

Trapping Errors and Debugging Code

Sub test() Dim num As Integer On Error GoTo exception num = "hi" MsgBox ("The value of num is " & num) Exit Sub exception: MsgBox ("type mismatch") num = 0 Resume Next End Sub Link to file

Trapping Errors and Debugging Code Run time errors Error handling code should be used whenever the program interacts with the user or other components of the computer On Error GoTo statement On Error GoTo line Enables the error-handling routine that starts at line specified in the required line argument. The line argument is any line label or line number. If a run-time error occurs, control branches to line, making the error handler active. The specified line must be in the same procedure as the On Error statement; otherwise, a compile-time error occurs.

Trapping Errors and Debugging Code

Public Sub test() Dim num As Variant Dim div As Variant Dim quo As Variant On Error GoTo exception ‘on division by zero error goto the label called exception num = InputBox("enter the dividend") div = InputBox("enter the divisor") quo = num / div ‘ line of code that could generate a run time error / division by zero MsgBox (num & " / " & div & " = " & quo) ‘out put the results of division Exit Sub ‘ program ends here if no error is encountered exception: MsgBox ("division by zero is not allowed") ‘Generate a warning message div = InputBox("enter the divisor") ‘ line or lines of code that fix the error Resume ‘go back to the line that caused the error End Sub Link to code

Trapping Errors and Debugging Code Avoiding run-time errors Check every input for data type, length, value and meaning Public Sub test() Dim num As Variant Dim div As Variant Dim quo As Variant num = InputBox("enter the dividend") div = InputBox("enter the divisor") ' Error handling code w/o the use of On Error Goto While (div = 0) If div = 0 Then MsgBox ("division by zero is not allowed") div = InputBox("enter the divisor") End If Wend 'end of error handling quo = num / div MsgBox (num & " / " & div & " = " & quo) End Sub

Trapping Errors and Debugging Code Avoiding run time errors……continued Provide easy to understand prompts for your application Make the prompts and error messages as specific as possible Offer to fix the problem automatically whenever possible Offer to retry the operation after you correct the error Reduce the chances of error by providing context sensitive help

Trapping Errors and Debugging Code Recovering from an error Adding recovery code means that you can count on your program to help you overcome problems with the system and keep your data safe. Two kinds of recovery code Code that recovers before the error happens Code that recovers after the error happens Common runtime error is running out of disk space Adding a drive checking feature Add a new library to your program Use Tools  References Command to display the references dialog box

Trapping Errors and Debugging Code

Public Sub DriveTest() ' Create a variable to hold the free space. Dim FreeSpace As Double 'changed from long as drives are larger ' Create a reference to the file system. Dim MyFileSystem As FileSystemObject ' Create a reference for the target drive. Dim MyDrive As Drive ' Create a dialog result variable. Dim Result As VbMsgBoxResult 'Provide a jump back point. DoCheckAgain: ' Fill these two objects with data so they show the ' available space on drive C. Set MyFileSystem = New FileSystemObject 'instantiate the fileSystemObject Set MyDrive = MyFileSystem.GetDrive("C") 'Set the GetDrive Property of the FSO Drive to C ' Determine the amount of free space. FreeSpace = MyDrive.AvailableSpace 'assign the AvailableSpace property value to FreeSpace

Trapping Errors and Debugging Code ' Make the check. If FreeSpace < Then ' The drive doesn't have enough space. Ask what to ' do. Result = MsgBox("The drive doesn't have enough " + _ "space to hold the data. Do you" + _ " want to correct the error?" + _ vbCrLf + _ Format(FreeSpace, "###,###") + _ " bytes available, " + _ "1,000,000,000 bytes needed.", _ vbYesNo Or vbExclamation, _ "Drive Space Error")

Trapping Errors and Debugging Code ' Determine if the user wants to correct the error. If Result = vbYes Then ' Wait for the user to fix the problem. MsgBox "Please click OK when you have freed" + _ " some disk space.", _ vbInformation Or vbOKOnly, _ "Retry Drive Check" ' Go to the fallback point. GoTo DoCheckAgain Else ' The user doesn't want to fix the error. MsgBox "The program can't save your data " + _ "until the drive has enough space.", _ vbInformation Or vbOKOnly, _ "Insufficient Drive Space" ' End the Sub. Exit Sub End If End Sub

Trapping Errors and Debugging Code Folder not found……………………Possible code Sub test4() Dim fso As New FileSystemObject 'create fso object variable Dim flds As Folders 'create f object variable Dim strText As String 'string var Dim i As Integer 'index var 'get folder method of fso returns a folder object corresponding to the folder in a specified path in this case ‘the folderspec is E:\ 'Subfolder Property Returns a Folders collection consisting of all folders contained in a specified 'folder, including those with Hidden and System file attributes set. Set flds = fso.GetFolder("e:\").SubFolders i = 1 'for every folder in the collection create a string that includes the path and size 'output the results to successive cells in worksheets("sheet1") For Each f In flds strText = f.Path & " - " & f.Size Worksheets("Sheet1").Cells(i, 1) = strText i = i + 1 Next End Sub

Trapping Errors and Debugging Code

Symantic Errors VBA Code and Logic are correct The meaning behind the code isn’t what was intended You used a Do Until loop when you needed a Do While loop

Trapping Errors and Debugging Code Symantic Errors VBA Code and Logic are correct The meaning behind the code isn’t what was intended You used a Do Until loop when you needed a Do While loop What is the difference ?

Trapping Errors and Debugging Code Public Sub test() Dim i As Integer Dim s1 As String Dim s2 As String Do Until (i < 20) 'Do until false s1 = s1 & i & " " i = i + 1 Loop MsgBox ("Do Until Loop: " & s1) WHAT IS THE OUTPUT FROM THIS CODE ? Do While (i < 20) 'Do while true s2 = s2 & i & " " i = i + 1 Loop MsgBox ("Do While Loop: " & s2) End Sub

Trapping Errors and Debugging Code More Error Handling Public Sub ErrorHandle() ' The variable that receives the input. Dim InNumber As Byte ‘will not allow a letter or special char ' Tell VBA about the error handler. On Error GoTo MyHandler ' Ask the user for some input. InNumber = InputBox("Type a number between 1 and " + _ "10.", "Numberic Input", "1")

Trapping Errors and Debugging Code ' Determine whether the input is correct. If (InNumber 10) Then ' If the input is incorrect, then raise an error. Err.Raise vbObjectError + 1, _ "ErrorCheck.ErrorCondition.ErrorHandle", _ "Incorrect Numeric Input. The number " + _ "must be between 1 and 10." Else ' Otherwise, display the result. MsgBox "The Number You Typed: " + CStr(InNumber), _ vbOKOnly Or vbInformation, _ "Successful Input" End If ' Exit the Sub. Exit Sub

Trapping Errors and Debugging Code ' The start of the error handler. MyHandler: ' Display an error message box. MsgBox "The program experienced an error." + vbCrLf + _ "Error Number: " + CStr(Err.Number) + vbCrLf + _ "Description: " + Err.Description + vbCrLf + _ "Source: " + Err.Source, _ vbOKOnly Or vbExclamation, _ "Program Error" ' Always clear the error after you process it. Err.Clear End Sub

Trapping Errors and Debugging Code Err Object Contains information about run-time errors. Remarks The properties of the Err object are set by the generator of an error — Visual Basic, an object, or the programmer. The default property of the Err object is Number. Because the default property can be represented by the object name Err, earlier code written using the Err function or Err statement doesn't have to be modified. When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and information that can be used to handle it. To generate a run-time error in your code, use the Raise method. The Err object's properties are reset to zero or zero-length strings ("") after an Exit Sub, Exit Function, Exit Property or Resume Next statement within an error-handling routine. Using any form of the Resume statement outside of an error-handling routine will not reset the Err object's properties. The Clear method can be used to explicitly reset Err. Use the Raise method, rather than the Error statement, to generate run- time errors for system errors and class modules. Using the Raise method in other code depends on the richness of the information you want to return. The Err object is an intrinsic object with global scope. There is no need to create an instance of it in your code.

Trapping Errors and Debugging Code Raise Method Generates a run-time error message Syntax: object.Raise number, source, description, helpfile, helpcontext User with the Err object (Err.raise) The error number can be custom by adding a number to the default value of the vbObjectError Note that the constant vbObjectError is a very large negative number

Trapping Errors and Debugging Code Never use the On Error GoTo 0 This statement turns off error handling Can cause a range of problems including Application failure Data loss Reporting errors Message Box Text File (chapter 10) (chapter 16)

Trapping Errors and Debugging Code Export file (Right click module, form, etc.)

Trapping Errors and Debugging Code Import files (form, basic, class) (r-click project explorer)

Trapping Errors and Debugging Code Built in Debugger Add by right clicking on the IDE menu and selecting Debug Set a breakpoint in your code by using the Breakpoint icon or double clicking the line The program halts at that point Debug your code By using Locals Watch Breakpoints You can use run with breakpoints and / or F8 to step into your code line by line Step over used to see effects of statements in the current module. Called subs functions still execute but you do not see them line by line

Trapping Errors and Debugging Code