JavaScript, Fourth Edition

Slides:



Advertisements
Similar presentations
Introducing JavaScript
Advertisements

 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - JavaScript: Introduction to Scripting Outline 7.1 Introduction 7.2 Simple Program: Printing.
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.
Tutorial 12: Enhancing Excel with Visual Basic for Applications
The Web Warrior Guide to Web Design Technologies
Microsoft VB 2005: Reloaded, Advanced Chapter 5 Input Validation, Error Handling, and Exception Handling.
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.
Chapter 16 Dynamic HTML and Animation The Web Warrior Guide to Web Design Technologies.
HTML Comprehensive Concepts and Techniques Second Edition Project 8 Integrating JavaScript with HTML.
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.
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, Third Edition
XP Tutorial 1 New Perspectives on JavaScript, Comprehensive1 Introducing JavaScript Hiding Addresses from Spammers.
Web Development & Design Foundations with XHTML Chapter 14 Key Concepts.
Copyright © Terry Felke-Morris WEB DEVELOPMENT & DESIGN FOUNDATIONS WITH HTML5 Chapter 14 Key Concepts 1 Copyright © Terry Felke-Morris.
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
Visual Basic Chapter 1 Mr. Wangler.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Chapter 5 Java Script And Forms JavaScript, Third Edition.
ASP.NET Programming with C# and SQL Server First Edition Chapter 6 Debugging and Error Handling.
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.
Copyright © Terry Felke-Morris WEB DEVELOPMENT & DESIGN FOUNDATIONS WITH HTML5 Chapter 14 Key Concepts 1 Copyright © Terry Felke-Morris.
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.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - JavaScript: Introduction to Scripting Outline 7.1 Introduction 7.2 Simple Program: Printing.
Automating Database Processing Chapter 6. Chapter Introduction Design and implement user-friendly menu – Called navigation form Macros – Automate repetitive.
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.
JavaScript, Fourth Edition Chapter 5 Validating Form Data with JavaScript.
Program Design and Coding
Microsoft Visual Basic 2012 CHAPTER THREE Program Design and Coding.
Microsoft Visual Basic 2010 CHAPTER THREE Program Design and Coding.
Debugging in Java. Common Bugs Compilation or syntactical errors are the first that you will encounter and the easiest to debug They are usually the result.
VB – Debugging Tools Appendix D. Why do we need debugging? Every program has errors, and the process of finding these errors is debugging Types of errors.
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.
 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.
JavaScript, Fourth Edition
JavaScript Introduction.  JavaScript is a scripting language  A scripting language is a lightweight programming language  A JavaScript can be inserted.
1 Chapter 3 – JavaScript Outline Introduction Flowcharts Control Structures if Selection Structure if/else Selection Structure while Repetition Structure.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
1 JavaScript in Context. Server-Side Programming.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Tutorial 10 Programming with JavaScript. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Learn the history of JavaScript.
Creating and Editing a Web Page
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.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 14 Event-Driven Programming with Graphical User Interfaces.
JavaScript, Sixth Edition
Tutorial 10 Programming with JavaScript. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Learn the history of JavaScript.
CIS 133 Mashup Javascript, jQuery and XML Chapter 8 Debugging and Error Handling.
JavaScript and AJAX 2nd Edition Tutorial 1 Programming with JavaScript.
XP Tutorial 10New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties.
Chapter 2: The Visual Studio.NET Development Environment Visual Basic.NET Programming: From Problem Analysis to Program Design.
 2001 Prentice Hall, Inc. All rights reserved. Outline 1 JavaScript.
Tutorial 10 Programming with JavaScript
CIS 133 Mashup Javascript, jQuery and XML
WEB PROGRAMMING JavaScript.
Tutorial 10 Programming with JavaScript
Presentation transcript:

JavaScript, Fourth Edition Chapter 8 Debugging and Error Handling

Objectives Study debugging concepts Learn how to trace error messages Learn how to use comments to locate bugs Trace errors with debugging tools Study exception and error handling Study additional debugging techniques JavaScript, Fourth Edition JavaScript, Fourth Edition 2 2

Understanding Debugging Syntax errors Occur when the interpreter fails to recognize code Can be caused by incorrect use of JavaScript code Run-time errors Occur when the JavaScript interpreter encounters a problem while a program is executing Not necessarily JavaScript language errors Occur when the interpreter encounters code that it cannot execute JavaScript, Fourth Edition

Understanding Debugging (continued) Logic errors Flaw in a program’s design that prevents the program from running as anticipated “Logic” refers to the execution of program statements and procedures In the correct order to produce the desired results JavaScript, Fourth Edition 4

Error Messages First line of defense in locating bugs Displayed in error message dialog boxes Line number in the document where error occurred Description of the error All error messages generated by a Web browser are run-time errors Run-time errors can be caused by syntax errors but not by logic errors JavaScript, Fourth Edition

Error Messages (continued) JavaScript, Fourth Edition 6

Error Messages (continued) JavaScript, Fourth Edition 7

Error Messages (continued) You can rely on error messages only to find the general location of an error in a program And not as the exact indicator of an error Browsers do not strictly enforce JavaScript syntax Mitigate bugs in JavaScript programs Always use good syntax Thoroughly test with every browser type and version Example: Moving Estimator Use error messages to help locate bugs JavaScript, Fourth Edition 8

Tracing Errors with the window.alert() Method Examining statements in an executing program window.alert() method One of the most useful ways to trace JavaScript code Place it at different points of your program Use it to display the contents of a variable, an array, or the value returned from a function Place multiple window.alert() methods in your code to check values as the code executes JavaScript, Fourth Edition 9

Tracing Errors with the window.alert() Method (continued) Drawback You must close each dialog box for your code to continue executing Use them selectively at key points Example Use alert dialog boxes to locate a bug in the Moving Estimator program JavaScript, Fourth Edition 10

Tracing Errors with the write() and writeln() Methods Trace a bug by analyzing a list of values Open a new browser window Use the write() and writeln() methods to print values to this separate window Driver program A simplified, temporary program for testing functions and other code JavaScript program that contains only the code you are testing JavaScript, Fourth Edition 11

Tracing Errors with the write() and writeln() Methods (continued) JavaScript, Fourth Edition 12

Using Comments to Locate Bugs Another method of locating bugs “Comment out” problematic lines Helps isolate the statement that is causing the error When you first receive an error message Start by commenting out only the statement specified by the line number in the error message JavaScript, Fourth Edition 13

Combining Debugging Techniques You can combine debugging techniques To aid in your search for errors Example Use comments to locate bugs in the Moving Estimator program JavaScript, Fourth Edition 14

Tracing Errors with Debugging Tools JavaScript Debugger Mozilla’s debugging tool Can be used to debug JavaScript code in Mozilla-based Web browsers, including Firefox Script Debugger Microsoft’s debugging tool Can be used with Internet Explorer to debug JavaScript code Can also debug VBScript, Java applets, JavaBeans, and ActiveX components JavaScript, Fourth Edition 15

Tracing Errors with Debugging Tools (continued) Examining your code manually Usually the first step to take with a logic error Debugging tools Several tools that help trace each line of code Create a much more efficient method of finding and resolving logic errors JavaScript, Fourth Edition 16

Understanding the JavaScript Debugger and Script Debugger Windows Using JavaScript Debugger Open the document you want to debug in Firefox Select JavaScript Debugger from the Tools menu To open a particular file, double-click it in Loaded Scripts view File opens in Source Code view (read-only file viewer) JavaScript, Fourth Edition 17

Understanding the JavaScript Debugger and Script Debugger Windows (continued) JavaScript, Fourth Edition 18

Understanding the JavaScript Debugger and Script Debugger Windows (continued) Using Script Debugger Open the document to debug in Internet Explorer Use Script Debugger submenu on the View menu Commands: Open and Break at Next Statement Code elements are distinguished by syntax color coding Example Open the Moving Estimator program in JavaScript Debugger and Script Debugger JavaScript, Fourth Edition 19

Understanding the JavaScript Debugger and Script Debugger Windows (continued) JavaScript, Fourth Edition 20

Setting Breakpoints Break mode Breakpoint Temporary suspension of program execution To monitor values and trace program execution Breakpoint Statement where execution enters break mode Once a program is paused at a breakpoint Use the debug tools to trace program execution JavaScript, Fourth Edition 21

Setting Breakpoints (continued) Entering break mode in JavaScript Debugger Hard breakpoints Can be set for executable statements within a local function And notify JavaScript Debugger to enter break mode before the statement executes Future breakpoints Can be set for any type of statement and notify JavaScript Debugger to enter break mode as soon as possible before the statement executes JavaScript, Fourth Edition 22

Setting Breakpoints (continued) Entering break mode in JavaScript Debugger (continued) Steps Open the document you want to debug Right-click the line in Source Code view where you want to set the breakpoint Select Set Breakpoint or Set Future Breakpoint Return to the Web browser window where the script is running and click the Reload icon or press Ctrl+R Continue command Executes the rest of the program normally or until another breakpoint is encountered JavaScript, Fourth Edition 23

Setting Breakpoints (continued) Entering break mode in JavaScript Debugger Stop command Ends a debugging session without executing the rest of the program Example Practice using breakpoints with the Moving Estimator program in Firefox Entering break mode in Script Debugger Steps Open the document in Internet Explorer and select Break at Next Statement JavaScript, Fourth Edition 24

Setting Breakpoints (continued) JavaScript, Fourth Edition 25

Setting Breakpoints (continued) Entering break mode in Script Debugger (continued) Steps Click the Refresh button or perform some event Document opens in the Script Debugger window at the first executed JavaScript statement Run command Executes the rest of the program normally or until another breakpoint is encountered Stop Debugging command Ends a debugging session without executing the rest of the program JavaScript, Fourth Edition 26

Setting Breakpoints (continued) Entering break mode in Script Debugger Example Practice using breakpoints with the Moving Estimator program in Internet Explorer JavaScript, Fourth Edition 27

Setting Breakpoints (continued) JavaScript, Fourth Edition 28

Stepping Through Your Scripts Step Into command Executes an individual line of code and then pauses until you instruct the debugger to continue Debugger stops at each line within every function of the JavaScript program Step Over command Allows you to skip function calls Program still executes function that you step over Step Out command Executes all remaining code in the current function JavaScript, Fourth Edition 29

Stepping Through Your Scripts (continued) Step Out command (continued) Debugger stops at the next statement in the calling function Example Practice tracing program execution using the Step commands JavaScript, Fourth Edition 30

Clearing Breakpoints Clearing breakpoints in JavaScript Debugger Right-click a line in Source Code view that contains the breakpoint Select Clear Breakpoint or Clear Future Breakpoint Remove all breakpoints Right-click anywhere in Breakpoints view and select Clear All Breakpoints or Clear All Future Breakpoints When you clear a hard breakpoint, it automatically changes to a future breakpoint JavaScript, Fourth Edition 31

Clearing Breakpoints (continued) Clearing breakpoints in Script Debugger Place cursor anywhere in a line that contains the breakpoint Select Toggle Breakpoint from the Debug menu Remove all breakpoints Select Clear All Breakpoints from the Debug menu JavaScript, Fourth Edition 32

Tracing Variables and Expressions Tracing variables and expressions in JavaScript Debugger Locals Variables view Displays all local variables within the currently executing function Helps you see how different values in the currently executing function affect program execution Watches view Monitors variables and expressions in break mode JavaScript, Fourth Edition 33

Tracing Variables and Expressions (continued) Tracing variables and expressions in JavaScript Debugger (continued) To open Watches view Select Watches from the Show/Hide submenu on the View menu To display the value of a variable or expression Right-click Watches view and select Add Watch Expression JavaScript, Fourth Edition 34

Tracing Variables and Expressions (continued) JavaScript, Fourth Edition 35

Tracing Variables and Expressions (continued) Tracing Variables and Expressions in Script Debugger Command window Monitors variables and expressions in break mode You can also change variables and expressions in break mode from within this window To display the value of a variable or expression Enter the variable or expression and press Enter To change the value of a variable Type the variable name in the Command window followed by an equal sign and the new value JavaScript, Fourth Edition 36

Tracing Variables and Expressions (continued) JavaScript, Fourth Edition 37

Tracing Variables and Expressions (continued) Example Use Watches view or the Command window to find a bug in the Moving Estimator program JavaScript, Fourth Edition 38

Examining the Call Stack The order in which procedures, such as functions, methods, or event handlers, execute in a program Each time a program calls a procedure Procedure is added to the top of the call stack In JavaScript Debugger Select Show/Hide on the View menu, and then click Call Stack In Script Debugger Select Call Stack from the View menu JavaScript, Fourth Edition 39

Handling Exceptions and Errors Bulletproofing Writing code to anticipate and handle potential problems One bulletproofing technique Validate submitted form data Exception handling Allows programs to handle errors as they occur in the execution of a program Exception Some type of error that occurs in a program JavaScript, Fourth Edition 40

Throwing Exceptions You execute code that may contain an exception in a try statement throw statement Indicates that an error occurred within a try block Example try { var email = formObject.value; var emailCheck = /^[_\w-]+(\.[_\w-]+)*@[\w-]+(\ .[\w-]+)*(\.[\D]{2,3})$/; if (emailCheck.test(email) == false) throw "One or more of the e-mail addresses you entered does not appear to be valid."; } JavaScript, Fourth Edition 41

Catching Exceptions Use a catch statement Example To handle, or “catch” the error Example catch(emailError) { window.alert(emailError) return false; } JavaScript, Fourth Edition 42

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 is evaluated with a try statement Example Modify the Moving Estimator program so it uses exception handling to prevent users from entering any values except numbers in the form’s text boxes JavaScript, Fourth Edition 43

Executing Final Exception Handling Tasks (continued) An Event object represents every event in JavaScript When calling an event handler function You can pass an argument named event An object that contains information about the event that occurred Use the onkeypress event with the Event object Object generated contains the Unicode character that represents the pressed key JavaScript, Fourth Edition 44

Implementing Custom Error Handling Primary purpose of exception handling To test specific types of code Catching errors with the onerror event onerror event Executes whenever an error occurs on a Web page You must call the onerror event handler as a property of the Window object Assign to the onerror event handler the name of a function that you want to handle JavaScript errors To prevent a Web browser from executing its own error handling functionality, you return a value of true JavaScript, Fourth Edition 45

Implementing Custom Error Handling (continued) Writing custom error handling functions JavaScript interpreter automatically passes three arguments to the custom error handling function Error message, URL, and line number Use these values in custom error handling function By adding parameters to the function definition Use parameters in your function to show a user the location of any JavaScript errors that may occur JavaScript, Fourth Edition 46

Implementing Custom Error Handling (continued) JavaScript, Fourth Edition 47

Additional Debugging Techniques Includes Checking XHTML elements Analyzing logic Testing statements with JavaScript URLs Reloading a Web page JavaScript, Fourth Edition 48

Checking XHTML Elements If you cannot locate a bug using any of the methods described in this chapter Perform a line-by-line analysis of your XHTML code Be sure that all necessary opening and closing tags are included Use the W3C Markup Validation Service to validate your Web page JavaScript, Fourth Edition 49

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

Testing Statements with JavaScript URLs For testing and executing JavaScript statements Without an XHTML document or JavaScript source file Useful if you are trying to construct the correct syntax for a mathematical expression You enter a JavaScript URL into your Web browser’s address box Just like a normal URL You can include multiple statements in a JavaScript URL if a semicolon separates them JavaScript, Fourth Edition 51

Reloading a Web Page Usually you can click the Reload or Refresh button in your browser to test code changes Web browser cannot always completely clear its memory of the remnants of an old bug Force the reload of a Web page by holding Shift key and clicking the browser’s Reload or Refresh button At times, even reopening the file does not completely clear the browser memory You must close the browser window completely May need to delete frequently visited Web pages JavaScript, Fourth Edition 52

Using a for...in Statement to Check Object Properties Sometimes program errors are caused by using the wrong object properties Or by assigning wrong value to an object property You can use a for...in loop To determine if values are being assigned to the correct properties in an object JavaScript, Fourth Edition 53

Identifying JavaScript Language and Browser Bugs You may encounter a bug in JavaScript language Or in a specific Web browser Try the following in Firefox window.status("Student Healthcare Services"); status("Student Healthcare Services"); defaultStatus("Student Healthcare Services"); No comprehensive or official list of JavaScript language bugs JavaScript, Fourth Edition 54

Summary Three types of errors can occur in a program: syntax errors, run-time errors, and logic errors The first line of defense in locating bugs in JavaScript programs are the error messages Tracing is the examination of individual statements in an executing program When using write() and writeln() methods to trace bugs, it is helpful to use a driver program JavaScript Debugger and Script Debugger tools JavaScript, Fourth Edition

Summary (continued) Break mode is the temporary suspension of execution to monitor values and trace execution Breakpoint is a statement in the code at which program execution enters break mode Step Into, Step Over, and Step Out commands JavaScript Debugger includes two views: Local Variables and Watches Call stack is the order in which procedures execute JavaScript, Fourth Edition

Summary (continued) Writing code that anticipates and handles potential problems is often called bulletproofing Exception handling try, throw, catch, and finally statements JavaScript includes an onerror event that executes whenever an error occurs on a Web page Additional methods and techniques for locating and correcting errors in your JavaScript programs Include checking XHTML elements, analyze logic, and test statements with JavaScript URLs JavaScript, Fourth Edition 57