www.cisdocs.com

Download Report

Transcript www.cisdocs.com

JavaScript, Fifth Edition
Chapter 8
Debugging and Error Handling
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
JavaScript, Fifth Edition
2
Introduction to Debugging
•
•
Programming languages have rules
– When rules are violated, it leads to unexpected results
Testing
–
•
Bug
–
•
Finding all errors to make sure the program works correctly, trying
every possible combination of input data and user actions you can
think of
Any program error that causes a program to function incorrectly
Debugging
–
Fixing all errors
–
Three kinds of errors to eliminate
–
–
–
Syntax
Run-time
Logic
JavaScript, Fifth Edition
3
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
JavaScript, Fifth Edition
4
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);
JavaScript, Fifth Edition
5
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);
JavaScript, Fifth Edition
6
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);
}
JavaScript, Fifth Edition
7
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
JavaScript, Fifth Edition
8
Code examination
JavaScript, Fifth Edition
9
Interpreting Error Messages
• First line of defense in locating bugs
– Browsers include tools for debugging code
– Error message dialog box displays
• Line number where error occurred - Not an exact
indicator
• Error description
JavaScript, Fifth Edition
10
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
JavaScript, Fifth Edition
11
Tracing Errors with the
window.alert() Method (cont’d.)
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);
}
JavaScript, Fifth Edition
12
Tracing Errors with the write() and
writeln() Methods
• Trace a bug by analyzing a list of values
– Write code to open a new browser window
– Use the write() or writeln() methods to print
values to this separate window
JavaScript, Fifth Edition
13
Tracing Errors with console.log
• Console.log method
– Similar to window.alert except eliminates pop-up window
– All errors written to developer tools console
function calculatePay() {
var payRate = 15; numHours = 40;
var grossPay = payRate * numHours;
console.log(grossPay);
var federalTaxes = grossPay * .06794;
var stateTaxes = grossPay * .0476;
var socialSecurity = grossPay * .062;
var medicare = grossPay * .0145;
var netPay = grossPay - federalTaxes;
console.log(netPay);
netPay *= stateTaxes;
console.log(netPay);
netPay *= socialSecurity;
console.log(netPay);
netPay *= medicare;
console.log(netPay);
return Math.round(netPay);
}
JavaScript, Fifth Edition
14
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
JavaScript, Fifth Edition
15
Combining Debugging Techniques
• Combine debugging techniques
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;
// netPay *= stateTaxes;
// netPay *= socialSecurity;
// netPay *= medicare;
// return Math.round(netPay);
}
JavaScript, Fifth Edition
16
Debugging Tools
JavaScript, Fifth Edition
17
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
JavaScript, Fifth Edition
18
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
JavaScript, Fifth Edition
19
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
JavaScript, Fifth Edition
20
Javascript debugger in Firefox
JavaScript, Fifth Edition
21
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
JavaScript, Fifth Edition
22
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
JavaScript, Fifth Edition
23
Setting Breakpoints (cont’d.)
• Click to the left of the line number that you want to
set the breakpoint on
– A dot will appear
Figure 8-14 Breakpoints in JavaScript Debugger
JavaScript, Fifth Edition
24
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
JavaScript, Fifth Edition
25
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
JavaScript, Fifth Edition
26
Clearing Breakpoints
• Clearing breakpoints in JavaScript Debugger
– click the Breakpoint to remove it
– Remove the checkmark in the breakpoint list
JavaScript, Fifth Edition
27
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
JavaScript, Fifth Edition
28
Tracing Variables and Expressions
(cont’d.)
– Click Add Watch Expression Watches view
– Type in the variable/expression
JavaScript, Fifth Edition
29
Tracing Variables and Expressions
(cont’d.)
– Run the program
– Observe variable as it changes
JavaScript, Fifth Edition
30
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
JavaScript, Fifth Edition
31
Handling exceptions and errors
JavaScript, Fifth Edition
32
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
JavaScript, Fifth Edition
33
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
JavaScript, Fifth Edition
34
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.
JavaScript, Fifth Edition
35
Exception programming syntax
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.
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
}
JavaScript, Fifth Edition
36
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
only
try {
var email = document.myform.emailfield.value;
var emailCheck = /^[_\w-]+(\.[_\w-]+)*@[\w-]
+(\.[\w-]+)*(\.[\D]{2,3})$/;
}
try with
throw
try {
var email = document.myform.emailfield.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, Fifth Edition
37
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(emailError) {
window.alert(emailError)
window.alert(emailError.name)
return false;
}
JavaScript, Fifth Edition
38
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
JavaScript, Fifth Edition
39
Custom error handling
JavaScript, Fifth Edition
40
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
JavaScript, Fifth Edition
41
Custom Events
• Events are listened for differently between the I.E.
browser and the W3C browsers
//W3C
if (window.addEventListener == true)
{
window.addEventListener(“error”,processErrors,true);
}
event
//I.E.
else if (window.attachEvent == true)
{
handler
window.attachEvent(“onerror”,processErrors);
}
JavaScript, Fifth Edition
42
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);
}
JavaScript, Fifth Edition
43
Additional Debugging Techniques
• Includes
–
–
–
–
Checking HTML elements
Analyzing logic
Testing statements with JavaScript URLs
Reloading a Web page
JavaScript, Fifth Edition
44
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 the W3C Markup Validation Service to validate
a Web page
JavaScript, Fifth Edition
45
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
JavaScript, Fifth Edition
46
Testing Statements with JavaScript
URLs
• JavaScript URL
– Testing and executing JavaScript statements
• Without HTML document or JavaScript source file
– Useful if trying to construct the correct syntax for a
mathematical expression
• Enter JavaScript URL into Web browser’s address
box
• Including multiple statements in a JavaScript URL
– Separate statements with a semicolon
JavaScript, Fifth Edition
47
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
JavaScript, Fifth Edition
48