01501_ch08 - CarlPetersheim.us

advertisement
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
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
3
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
5
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
• 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
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
– 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
• 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
– 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
50
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
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
55
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
56
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
Download