CIS 133 Mashup Javascript, jQuery and XML Chapter 8 Debugging and Error Handling.

Slides:



Advertisements
Similar presentations
Introducing JavaScript
Advertisements

COMPUTER PROGRAMMING I Essential Standard 5.02 Understand Breakpoint, Watch Window, and Try And Catch to Find Errors.
Why care about debugging? How many of you have written a program that worked perfectly the first time? No one (including me!) writes a program that works.
Chapter 3: Editing and Debugging SAS Programs. Some useful tips of using Program Editor Add line number: In the Command Box, type num, enter. Save SAS.
The Web Warrior Guide to Web Design Technologies
Microsoft VB 2005: Reloaded, Advanced Chapter 5 Input Validation, Error Handling, and Exception Handling.
Lecture Roger Sutton CO331 Visual programming 15: Debugging 1.
1 Outline 13.1Introduction 13.2A Simple Program: Printing a Line of Text in a Web Page 13.3Another JavaScript Program: Adding Integers 13.4Memory Concepts.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
The IDE (Integrated Development Environment) provides a DEBUGGER for locating and correcting errors in program logic (logic errors not syntax errors) The.
Tutorial 10 Programming with JavaScript
1 Chapter 4 The Fundamentals of VBA, Macros, and Command Bars.
How to Debug VB .NET Code.
Visual Basic Debugging Tools Appendix D 6/27/20151Dr. Monther Aldwairi.
Chapter 2: The Visual Studio.NET Development Environment Visual Basic.NET Programming: From Problem Analysis to Program Design.
JavaScript, Fourth Edition
XP Tutorial 1 New Perspectives on JavaScript, Comprehensive1 Introducing JavaScript Hiding Addresses from Spammers.
COMPREHENSIVE Excel Tutorial 8 Developing an Excel Application.
Chapter 9 Introduction to ActionScript 3.0. Chapter 9 Lessons 1.Understand ActionScript Work with instances of movie clip symbols 3.Use code snippets.
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
ASP.NET Programming with C# and SQL Server First Edition Chapter 6 Debugging and Error Handling.
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.
Enhancing User Interaction Through Programming
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
Lesson 19. JavaScript errors Since JavaScript is an interpreted language, syntax errors will usually cause the script to fail. Both browsers will provide.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
CSS Class 7 Add JavaScript to your page Add event handlers Validate a form Open a new window Hide and show elements Swap images Debug JavaScript.
CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction.
1 JavaScript in Context. Server-Side Programming.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
Tutorial 10 Programming with JavaScript. XP Objectives Learn the history of JavaScript Create a script element Understand basic JavaScript syntax Write.
Tutorial 10 Programming with JavaScript
Done by: Hanadi Muhsen1 Tutorial 1.  Learn the history of JavaScript  Create a script element  Write text to a Web page with JavaScript  Understand.
Using Client-Side Scripts to Enhance Web Applications 1.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
Microsoft Visual Basic 2010 CHAPTER THREE Program Design and Coding.
Chapter 5: Windows and Frames
XP Tutorial 6 New Perspectives on JavaScript, Comprehensive1 Working with Windows and Frames Enhancing a Web Site with Interactive Windows.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 8 Debugging, Creating Executable Files, and Distributing a Windows Application.
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
XP Tutorial 8 Adding Interactivity with ActionScript.
 2000 Deitel & Associates, Inc. All rights reserved. Outline 8.1Introduction 8.2A Simple Program: Printing a Line of Text in a Web Page 8.3Another JavaScript.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
JavaScript, Fourth Edition
1 Debugging and Syntax Errors in C++. 2 Debugging – a process of finding and fixing bugs (errors or mistakes) in a computer program.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
1 JavaScript in Context. Server-Side Programming.
Tutorial 10 Programming with JavaScript. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Learn the history of JavaScript.
Understanding JavaScript and Coding Essentials Lesson 8.
Debugging tools in Flash CIS 126. Debugging Flash provides several tools for testing ActionScript in your SWF files. –The Debugger, lets you find errors.
CHAPTER 10 ERROR HANDLING & DEBUGGING JavaScript can be hard to learn. Everyone makes mistakes when writing it.
JavaScript, Sixth Edition
Text INTRODUCTION TO ASP.NET. InterComm Campaign Guidelines CONFIDENTIAL Simply Server side language Simplified page development model Modular, well-factored,
Tutorial 10 Programming with JavaScript. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Learn the history of JavaScript.
JavaScript and AJAX 2nd Edition Tutorial 1 Programming with JavaScript.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 2: The Visual Studio.NET Development Environment Visual Basic.NET Programming: From Problem Analysis to Program Design.
© 2010 Robert K. Moniot1 Chapter 6 Introduction to JavaScript.
Tutorial 10 Programming with JavaScript
Computer Programming I
Scripts & Functions Scripts and functions are contained in .m-files
CIS 133 Mashup Javascript, jQuery and XML
Variables and Arithmetic Operations
WEB PROGRAMMING JavaScript.
Tutorial 10 Programming with JavaScript
Presentation transcript:

CIS 133 Mashup Javascript, jQuery and XML Chapter 8 Debugging and Error Handling

2 Objectives Tuesday: –Study debugging concepts, including error types –Learn how to trace error messages –Use comments to locate bugs –Trace errors with debugging tools Thursday –Study exception and error handling

3 Introduction to Debugging Programming languages have rules –When rules are violated, it leads to unexpected results Testing –Finding all errors to make sure the program works correctly, trying every possible combination of input data and user actions you can think of Bug –Any program error that causes a program to function incorrectly Debugging –Fixing all errors –Three kinds of errors to eliminate –Syntax –Run-time –Logic

4 Identifying Syntax Errors Syntax errors –Occur when interpreter fails to recognize code –Easiest to find and fix –Causes Incorrect use of JavaScript code References to non-existent objects, methods, variables

5 Identifying Syntax Errors Common causes of Syntax errors –Misspelling keywords –Forgetting a parenthesis –Breaking a statement into 2 or more lines –Quotation mark mismatch –Using one equal sign instead of 2 –Forgetting to use parseInt or parseFloat Example: vr divisionResult = 10 / 2; document.write("Ten divided by two is equal to " + divisionResult);

6 Identifying Run-Time Errors Run-time errors –Occur when interpreter encounters a problem while program executing Not necessarily JavaScript language errors –Occur when interpreter encounters code it cannot execute –Run-time errors do not violate syntax rules Example: function x(num1, num2) { var divisionResult = num1 / num2; document.write(num1 + “ divided by “ + num2 + “ is equal to “ + divisionResult); } X(10,2);

7 Identifying Logic Errors Logic - Execution of program statements and procedures in the correct order to produce the desired results Logic errors –Flaw in a program’s design which prevents a program from producing the anticipated result –Example 1: var divisionResult = 10 * 2; document.write("Ten divided by two is equal to " + divisionResult); –Example 2: for (var count = 10; count >= 0; count) { window.alert("We have liftoff in " + count); }

8 Interpreting Error Messages First line of defense in locating bugs –Browsers include tools for debugging code –Console Logs display Line number where error occurred - Not an exact indicator – general location in program Error description

9 Interpreting Error Messages Run-time errors –Error messages generated by a web browser Can be caused by syntax errors but not by logic errors –Example: function missingClosingBrace() { var message = "This function is missing a closing brace."; window.alert(message);

10 Interpreting Error Messages (cont’d.) Browsers do not strictly enforce JavaScript syntax Mitigating bugs in JavaScript programs –Always use good syntax – write GOOD code –Thoroughly test with every browser type, version

Code examination 11

12 Using Basic Debugging Techniques Syntax errors can be difficult to pinpoint A few common techniques are helpful in tracking down bugs

13 Tracing Errors Tracing –Examines statements in an executing program –window.alert() method Place at different points within program –Add statement to code at key points to »Prove that the program is really at that point in the logic »display variable values –Must understand what program is trying to do and must understand sequence of code events –Drawback Must close each dialog box for code to continue executing

14 function calculatePay() { var payRate = 15; numHours = 40; var grossPay = payRate * numHours; window.alert(grossPay); var federalTaxes = grossPay *.06794; var stateTaxes = grossPay *.0476; var socialSecurity = grossPay *.062; var medicare = grossPay *.0145; var netPay = grossPay - federalTaxes; window.alert(netPay); netPay *= stateTaxes; window.alert(netPay); netPay *= socialSecurity; window.alert(netPay); netPay *= medicare; window.alert(netPay); return Math.round(netPay); } Tracing Errors with the window.alert() Method (cont’d.)

15 Tracing Errors with the console.log() Method Trace a bug by analyzing a list of values –Similar to window.alert except eliminates pop-up window Logging –writing values directly to the console using the console.log() method –syntax: console.log( value); –can log string literal, variable value, or combination

16 Tracing Errors with the console.log() Method (cont’d.) function calculatePay() { var payRate = 15; numHours = 40; var grossPay = payRate * numHours; console.log("grossPay is " + grossPay); var federalTaxes = grossPay *.06794; var stateTaxes = grossPay *.0476; var socialSecurity = grossPay *.062; var medicare = grossPay *.0145; var netPay = grossPay - federalTaxes; console.log("grossPay minus federalTaxes is " + netPay); netPay *= stateTaxes; console.log("netPay minus stateTaxes is " + netPay); netPay *= socialSecurity; console.log("netPay minus socialSecurity is " + netPay); netPay *= medicare; console.log("netPay minus medicare is " + netPay); return netPay; } calculatePay();

17 Tracing Errors with the console.log() Method (cont’d.) Contents of the console after executing the calculatePay() function

18 Tracing Errors with the console.log() Method (cont’d.) Driver program –simplified, temporary program –contains only the code you are testing

19 Using Comments to Locate Bugs Another method of locating bugs –“Comment out” problematic lines Helps isolate statement causing the error When error message first received –Start by commenting out only the statement specified by the line number in the error message –Continue commenting lines until error eliminated

20 Combining Debugging Techniques Combine debugging techniques –Aid in search for errors Example: –Use comments combined with an alert box or log message to trace errors in the calculatePay() function

21 function calculatePay() { var payRate = 15; var numHours = 40; var grossPay = payRate * numHours; window.alert(grossPay); // var federalTaxes = grossPay *.06794; // var stateTaxes = grossPay *.0476; // var socialSecurity = grossPay *.062; // var medicare = grossPay *.0145; // var netPay = grossPay – federalTaxes; // netPay *= stateTaxes; // netPay *= socialSecurity; // netPay *= medicare; // return Math.round(netPay); } Combining Debugging Techniques (cont’d.)

22 Dependencies Relationship in which one statement depends on another statement executing successfully Can make debugging more challenging Important to retest program after fixing a bug to ensure other parts aren't affected by change

Debugging Tools 23

24 Tracing Errors with Debugging Tools Available in current versions of all modern browsers –Internet Explorer (IE) –Chrome –Firefox Accessible through same panel that opens when you use the console

25 Debugging Tools Examining code manually –Usually first step taken with a logic error –Works fine with smaller programs Debugging tools –Help trace each line of code –More efficient method of finding and resolving logic errors –Hardest thing is how to launch the tool –Next hardest thing is how to use the tool

26 Tracing Errors with Debugging Tools JavaScript Debuggers –Most newer browser have built in debugging tools Mozilla-based Web browsers, including Firefox. Click on Developer->web console Microsoft’s debugging tool – F12 –Third-party debuggers Add-ons for a particular browser Firebug is most common one used for Firefox Debug HTML, CSS, Web page scripts

27 Understanding the IE, Firefox, and Chrome Debugger Windows Using Debugger Windows –Open a document to debug in a browser –Use keyboard shortcut or menu to open debugger Steps to open debuggers in IE, Firefox, and Chrome

28 Understanding the IE, Firefox, and Chrome Debugger Windows (cont’d.) Debugger window –Usually separate pane attached to bottom of browser window –Can also detach pane into separate window

29 Understanding the IE, Firefox, and Chrome Debugger Windows (cont’d.) Internet Explorer –Shows HTML code by default –Click View sources to select a different file

30 Understanding the IE, Firefox, and Chrome Debugger Windows (cont’d.) Firefox –Lists JavaScript files alphabetically –Click a filename to see its contents

31 Understanding the IE, Firefox, and Chrome Debugger Windows (cont’d.) Chrome –Displays no files by default –press Ctrl + O (Win) or command + O (Mac) to select from list of associated files

Features of debugging tools Setting break points –temporarily stopping the program Stepping through the code –Executing code one line at a time Watching variables as they change Watching expressions as they execute 32

Javascript debugger in Firefox 33

34 Setting Breakpoints Break mode –Temporary suspension of program execution –Used to monitor values and trace program execution Breakpoint –Statement where execution enters break mode When program paused at a breakpoint –Use debug tools to trace program execution

35 Setting Breakpoints (cont’d.) Entering break mode in JavaScript Debugger –Hard breakpoints Set for executable statements within a local function Notify JavaScript Debugger to enter break mode before the statement executes –Conditional breakpoints Set for any type of statement, based on a condition occurring Notify JavaScript Debugger to enter break mode as soon as possible before the statement executes

Click to the left of the line number that you want to set the breakpoint on –A dot will appear 36 Figure 8-14 Breakpoints in JavaScript Debugger Setting Breakpoints (cont’d.)

37 tuba.js execution stopped at the line 63 breakpoint Setting Breakpoints (cont’d.)

38 Clearing Breakpoints Clearing breakpoints in JavaScript Debugger – click the Breakpoint to remove it –Remove the checkmark in the breakpoint list

39 Stepping Through Your Scripts Step Into button –Executes an individual line of code Pauses until instructed to continue –Debugger stops at each line within every function Step Over button –Allows skipping of function calls –Program still executes function stepped over Step Out button –Executes all remaining code in the current function –Debugger stops at next statement in the calling function

Stepping Through Your Scripts Once a breakpoint is encountered, the toolbar changes –Continue button Executes the rest of the program normally or until another breakpoint encountered –Stop/Pause Debugging button Ends a debugging session without executing the rest of the program 40

41 Tracing Variables and Expressions Tracing variables and expressions in JavaScript Debugger –Locals Variables view Displays all local variables within the currently executing function Shows how different values in the currently executing function affect program execution –Watches view Monitors variables and expressions in break mode

42 Tracing Variables and Expressions (cont’d.) –To access watch list IE –Displayed by default on right side of pane –In break mode, local and global variables displayed Firefox –Click Expand Panes button –Shows watch and variables list on right side of pane Chrome –Displayed by default on right side of pane

43 Tracing Variables and Expressions (cont’d.) –Click Add Watch Expression Watches view –Type in the variable/expression

44 Tracing Variables and Expressions (cont’d.) –Run the program –Observe variable as it changes

45 Examining the Call Stack Call stack –Order in which procedures (functions, methods, event handlers) execute in a program Each time a program calls a procedure: –Procedure added to top of the call stack

46 Examining the Call Stack IE and Chrome –Call stack list displayed to right of code Firefox –Call stack list displayed above code

Handling exceptions and errors 47

48 Handling Exceptions and Errors Bulletproofing –Writing code to anticipate and handle potential problems –One bulletproofing technique Validate submitted form data Exception –Error occurring in a program Exception handling –Allows programs to handle errors as they occur in program execution

How errors are handled When an error occurs, JavaScript will normally stop, and generate an error message. –The technical term for this is: JavaScript will throw an error. You can handle errors in a custom way –The throw statement allows you to create a custom error. –The technical term for this is: throw an exception If you use throw together with try and catch, you can control program flow and generate custom error messages. 49

Exception programming syntax try { statements to execute if error occurs.. throw.. } catch { errors to act upon from try block } finally { code that executes regardless of errors; cleanup code } 50 The try statement lets you test a block of code for errors. The catch statement lets you handle the error. The throw statement lets you create custom errors. The finally statement lets you execute code, after try and catch, regardless of the result.

51 Try code and throw exceptions try statement :executes code which might contain a possible exception throw statement: Indicates an error occurred within a try block –Creates an ERROR object, which has two properties: message and name, which can be used to catch an error you didn’t throw try { var = document.myform. field.value; var Check = +(\.[\w-]+)*(\.[\D]{2,3})$/; } try { var = document.myform. field.value; var Check = +(\.[\w-]+)*(\.[\D]{2,3})$/; if ( Check.test( ) == false) throw "One or more of the addresses you entered does not appear to be valid."; } try only try with throw

52 Catching Exceptions Use a catch statement –Handles, or “catches” the error –The ERROR is caught as a parameter that you assign a name to Syntax: catch(error) { statements; } Example: catch( Error) { window.alert( Error) window.alert( Error.name) return false; }

53 Executing Final Exception Handling Tasks finally statement –Executes regardless of whether its associated try block throws an exception –Used to perform some type of cleanup Or any necessary tasks after code evaluated with a try statement

Custom error handling 54

55 Implementing Custom Error Handling Primary purpose of exception handling –Prevent users from seeing errors occurring in programs –Provide graceful way to handle errors Reason for using exception handling with JavaScript –Evaluate user input Programmers may write their own error-handling code –Can write user-friendly messages –Provides greater control over any errors

56 Executing Final Exception Handling Tasks (cont’d.) Every event in JavaScript has an event object associated with it –Mouse click –link hover –Document load –Window close Javascript includes an ERROR event that executes whenever an error occurs on the web page Can “listen” for that event to occur and implement your own custom error handling –Preventing the Web browser from executing its own error handling functionality –

Custom Events 57 event handler Events are listened for differently between the I.E. browser and the W3C browsers //W3C if (window.addEventListener == true) { window.addEventListener(“error”,processErrors,true); } //I.E. else if (window.attachEvent == true) { window.attachEvent(“onerror”,processErrors); }

58 Implementing Custom Error Handling (cont’d.) Writing custom error-handling functions –JavaScript interpreter automatically passes three arguments to the custom error handling function Error message, URL, line number –Use these values in custom error handling function By adding parameters to the function definition –Use parameters in the function Show a user the location of any JavaScript errors that may occur –Return return a value of true from the onerror event handler function function processErrors(msg,URL,lineNum) { window.alert( “failure at line: “ + lineNum); }

59 Additional Debugging Techniques Includes –Checking HTML elements –Analyzing logic –Testing statements with console command line –Using the debugger statement –Executing code in strict mode –Linting –Reloading a Web page

60 Checking HTML Elements If a bug cannot be located –Perform a line-by-line analysis of the HTML code –Ensure all necessary opening and closing tags included Use code editor specialized for web development –Highlights syntax errors as you type Use the W3C Markup Validation Service to validate a Web page

61 Analyzing Logic Some JavaScript code errors stem from logic problems –Can be difficult to spot using tracing techniques Analyze each statement on a case-by-case basis

62 Testing Statements with JavaScript URLs Command Lines –Testing and executing JavaScript statements Without HTML document or JavaScript source file –Useful if trying to construct the correct syntax for a mathematical expression Two ways: –Enter JavaScript URL into Web browser’s address box Separate statements with a semicolon –Enter JavaScript statement at command line in web browsers console

63 Using the debugger statement When you include the debugger statement in your code –web browser stops executing JavaScript code when it reaches the debugger statement –equivalent of a breakpoint that's part of your JavaScript code

64 Using Strict Mode Strict mode –Removes some features from JavaScript –Requires more stringent syntax for other features Example: must always use var to declare variables Many removed or altered features in strict mode are known to cause hard to find bugs Include statement "use strict"; –Including at start of script section requests strict mode for all code in that section –Including at start of code block in function requests strict mode just for that function

65 Linting Running code through a program that flags some common issues that may affect code quality jslint is a commonly used linting program Similar result to using strict mode, but generates a report containing line numbers

66 Reloading a Web Page Usually click the browser Reload or Refresh button Web browser cannot always completely clear its memory –Remnants of an old bug may remain –Force Web page reload Hold Shift key and click the browser’s Reload or Refresh button May need to close browser window completely May need to delete frequently visited Web pages