1 / 56

JavaScript, Fourth Edition

JavaScript, Fourth Edition . 2. JavaScript, Fourth Edition . 2. 2. Objectives. Study debugging conceptsLearn how to trace error messagesLearn how to use comments to locate bugsTrace errors with debugging toolsStudy exception and error handlingStudy additional debugging techniques . JavaScript, Fourth Edition .

adamdaniel
Download Presentation

JavaScript, Fourth Edition

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


    1. JavaScript, Fourth Edition Chapter 8 Debugging and Error Handling

    2. JavaScript, Fourth Edition 2 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

    3. JavaScript, Fourth Edition 3 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

    4. 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

    5. JavaScript, Fourth Edition 5 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

    6. Error Messages (continued)

    7. Error Messages (continued)

    8. 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

    9. Tracing Errors with the window.alert() Method Tracing 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

    10. 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

    11. 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

    12. Tracing Errors with the write() and writeln() Methods (continued)

    13. 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

    14. 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

    15. 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

    16. 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

    17. 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)

    19. 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

    21. Setting Breakpoints Break mode 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

    22. 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

    23. 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

    24. 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

    25. Setting Breakpoints (continued)

    26. 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

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

    28. Setting Breakpoints (continued)

    29. 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

    30. 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

    31. 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

    32. 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

    33. 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

    34. 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

    35. Tracing Variables and Expressions (continued)

    36. 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

    37. Tracing Variables and Expressions (continued)

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

    39. Examining the Call Stack 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

    40. 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

    41. 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."; }

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

    43. 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

    44. 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

    45. 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

    46. 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

    47. Implementing Custom Error Handling (continued)

    48. Additional Debugging Techniques

    49. 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

    50. JavaScript, Fourth Edition 50 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

    51. Testing Statements with JavaScript URLs JavaScript URL 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

    52. 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

    53. 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

    54. 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

    55. JavaScript, Fourth Edition 55 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

    56. JavaScript, Fourth Edition 56 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

    57. 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

More Related