73
Sahar Mosleh Page California State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Embed Size (px)

Citation preview

Page 1: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 1

Common Mistakes,Debugging, andError Handling

Page 2: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 2

Some Common Mistakes

• It’s time to do a rundown of seven common mistakes. Some of these you’ll learn to avoid as you become more experienced, but others may haunt you forever!

Page 3: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 3

1: Undefined Variables

• JavaScript is actually very easygoing when it comes to defining your variables before assigning values to them. For example, the following will implicitly create a new variable abc and assign it to the value 23.

• Although strictly speaking, we should define the variable explicitly.

• (Actually, whether you use the var keyword has a consequence on the scope that the variable has, so in fact it is always best to use the var keyword.)

• However, if a variable is actually used before it has been defined, an error will arise. For example, the following code will cause the error the variable abc has not been previously defined (explicitly or implicitly)

Page 4: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 4

Page 5: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 5

• In addition, we must remember that function definitions also have parameters, which if not declared correctly can lead to the same type of error. Take a look at the following code:

• if we call this function, we get an error message similar to

Page 6: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 6

• The error here is actually a simple typo in the function definition. The first parameter has the typo:

• It should read numberofQuestions not numberOfQustions. What can be confusing with this type of error is that although the browser tells us the error is on one line, in fact the source of the error is on some other line.

Page 7: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 7

2: Case Sensitivity

• This is a major source of errors, particularly because it can be difficult to spot at times. For example, spot the three case errors in the following code:

• The first error is that we have typed If rather than if. However, JavaScript won’t tell us that the error is an incorrect use of case, but instead IE will tell us “Object expected” and Netscape will tell us that “if is not defined.” Although error messages give us some idea of what’s gone wrong, they often do so in an oblique way. in this case IF thinks we are trying to use an object called an If object and Netscape thinks we are trying to use an undefined variable called If.

Page 8: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 8

• Okay, with that error cleared, we come to the next error, not one of JavaScript syntax, but a logic error Remember that Paul does not equal paul in JavaScript, so myName = = “paul” is false, even though it’s quite likely that we didn’t care whether it was paul or Paul. This type of error will result in no error message at all, just the code not executing as we’d planned.

• The third fault is with the touppercase () method of the string object contained in myName. We’ve written touppercase, with the c in lowercase. IE will give us the message, “Object doesn’t support this property or method” and Netscape will report that, “myName.toUppercase is not a function.”

• On first glance it would be easy to miss such a small mistake and start checking our JavaScript reference guide for that method. We might wonder why it’s there, but our code is not working. Again we always need to be aware of case, something that even experts get wrong from time to time.

Page 9: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 9

3: Incorrect Number of Closing Braces

• In the following code we define a function and then call it.

However, there’s a deliberate mistake.

• See if you can spot where it is. If we properly format the code

it makes it much easier tospot where the error is.

• Now we can see that we’ve forgotten to mark the end ofthe function with a closing curly brace.

Page 10: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 10

4: Missing + Signs When Concatenating

• In the following code, there’s a deliberate concatenation mistake.

• There should be a + operator between and myotherstring in the fourth line of code.

• Although easy to spot in just a few lines of code, this kind of mistake can be harder to spot in large chunks of code. Also the error message that a mistake like this causes can be misleading. Load this code into a browser and we’ll be told “Error Expected” by IE and “Missing ; before statement” by Netscape. it’s surprising how often this error crops up.

Page 11: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 11

5: Equals Rather than Is Equal to

• Take a look at the following code:

• We’d expect, at first glance, that the alert () method in the else part of the if statement would execute telling us that the number in myNumber is 99, but it won’t. We’ve made the classic one equals sign instead of two equals signs mistake.

• Hence, instead of comparing myNumber with 101, we have set myNumber to equal 101.

Page 12: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 12

• What makes it even trickier is that no error message will be raised; it is just our data and logic that will suffer. Assigning a variable a value in an if statement may be perverse, but it’s perfectly legal so there will be no complaints from JavaScript. When embedded in a large chunk of code, a mistake like this is easily overlooked. Just remember next time your program’s logic seems crazy, that it’s worth checking for this error.

• One piece of good news is that NN 6 and 7 will issue a warning when we make this mistake along the lines of: “test for equality (= =) mistyped as assignment (=)?“.

• Note that it’s only a warning and not an error, so no error messages will appear The difference between warnings and errors is that a warning is issued for code that is syntactically correct, but that does appear to be flawed logically. Errors are where the syntax of the code is invalid. We’ll see later how we can use the Netscape JavaScript console to view errors and warnings.

Page 13: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 13

6: Incorrect Number of Closing Parentheses • Take a look at the following code:

• Spot the mistake? The problem is we’ve missed a parenthesis at the beginning. We want myvariable + 12 to be calculated before the division by myothervariable is calculated, so quite rightly we know we need to put it in parentheses.

(myvariable + 12) / myOthervariable

• However, the if statement’s condition must also be in parentheses. Not only is the initial parenthesis missing, but also we have one more closing parenthesis than we have opening parentheses; the numbers must match. For each parenthesis opened, there must be a corresponding closing parenthesis. Our code should be as follows:

Page 14: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 14

7: Using a Method as a Property and Vice Versa

• Our final common error is where either we forget to put parentheses after a method with no parameters, or we use a property and do put parentheses after it.

• When calling a method we must always have parentheses following its name; otherwise JavaScript thinks that it must be a property. For example, examine the following code:

• in the first line we have used the Date constructor, which is simply a method of the Date object, with no parentheses. On the second line, we call the getMonth () method of the Date object, except that we’ve forgotten the parentheses here also.

Page 15: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 15

• This is how lines should be:

• Just as we should always have parentheses after a method, we should never have parentheses after a property, otherwise JavaScript thinks we are trying to use a method of that object:

• in the second line we have used parentheses after the length property, making JavaScript think it is a method. We should have written it like this:

• This mistake may seem like an obvious one in two lines of code, but it’s easy to slip up when we’re pounding out lots and lots of code.

Now that we’ve seen these top seven mistakes, we’ll take a look at one way to make remedying these errors easier. This is through the Microsoft script debugger.

Page 16: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 16

Microsoft Script Debugger

• The Microsoft script debugger for use with IE is a very useful tool for helping discover what’s gone wrong and why. Using it, you can halt the execution of your script and then step through code line by line to see exactly what is happening.

• You can also find out which data is being held in variables and execute statements on the fly. Without the script debugger the best we can do is use the alert () method in our code to show the state of variables at various points.

Page 17: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 17

Obtaining the Script Debugger

• We can currently download the script debugger from the following URL if we are running Windows 98 or ME:

http://www.microsoft.com/downloads/details.aspx?familyid=e606e71f-ba7f-471e- a57d-f2216d81ec3d&languageid=f49e8428-7071-4979-8a67-3cffcbOc2524&displaylang=en

• Use this URL when running Windows NT, 2000, or XP:

http://www.microsoft.com/downloads/details.aspx?Familyld=2F4653E0-94FD-4569-33C4- DFFDF19CCD99&displaylang=en

• if these URLs change, a search on the Microsoft website, for “script debugger” ought to find its new home.

http: / /www . microsoft .com

Page 18: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 18

• If Personal Web Sewer (PWS) or internet information Services IIS are installed, which we’ll be looking at in a later chapter, the script debugger should already be installed. Other programs, such as Visual interDev, which is part of Visual Studio, also automatically install the script debugger.

• In addition, Windows 2000 automatically comes with the script debugger, although it may not be set up on your system. To install it open the Control Panel and choose Add/Remove Programs. Click the Add/Remove Windows Components button, and in the window that opens, scroll down the list to the script debugger. if it is not checked, then check it and click Next to install it.

• To see if the script debugger is already installed, open up internet Explorer and select the View menu. if one of the menu options is Script Debugger, the debugger is installed, if we do not find this menu option, it is still possible that the script debugger is already installed, but disabled. See the end of the next section for how to enable the script debugger, and then check for the menu option again.

Page 19: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 19

Page 20: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 20

Opening a Page in the Debugger

• We can open a page in the script debugger in a number of ways, but here we’ll just look at the three most useful. However, before we start let’s create a page we can debug. Notice that we have made a deliberate typo in line 14. Be sure to include this typo if creating the page from scratch.

Page 21: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 21

Page 22: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 22

• When we load this page into internet Explorer, we’ll discover the first way of activating the script debugger: automatically when there is an error in our code.

• We should see a message box, asking whether we wish to debug. Click Yes. Note that if Visual Studio is installed, a second dialog box will give us the option of opening a project. Just click No at that point.

Page 23: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 23

• The debugger has opened and stopped on the line where the error is and highlighted it in yellow, although this may not be obvious from the black and white screenshots in this chapter.

• The deliberate mistake is that we’ve written documents write rather than document write. The view is read-only so we can’t edit it here, so we need to return to our text editor to correct it. Let’s do that, and then reload the page.

Page 24: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 24

Page 25: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 25

• Having corrected the mistake and reloaded the page, we should see the two times table in our web page.

Page 26: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 26

• The second method we’re going to use to open the debugger is to load the page we want to debug into our browser; then we use the Break at Next Statement menu option under Script Debugger on internet Explorer’s View menu.

Page 27: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 27

• We’ve already got debug_timesteble.htm loaded, so select View -->

ScriptDebugger --> Break at Next Statement. Not much appears to happen, but reload the page by clicking the refresh icon or pressing F5, and the debugger will open at the next JavaScript statement executed.

• Where the next JavaScript statement occurs in our page depends on our code. if we have code in the page other than a function or code connected to an event handler, the first line the browser executes will be the next JavaScript statement. in our case, this is the code calling the function

Page 28: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 28

• If there is no code in the page except code inside event handlers or functions, the next statement executed will be that fired in an event handler, such as the window object’s on load event handler or a button’s onclick event handler

• Note that with some set-ups of the script debugger, the browser brings up a dialog box saying that an exception of type “Runtime Error” was not handled. This does not mean that there is an error in the code, but simply is the way Break at Next Statement works.

• As we can see on the next slide, the next statement executed in our example occurs when the browser reaches the script embedded in our web page that calls the writeTimesTable () function, again highlighted in yellow by the debugger.

Page 29: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 29

Page 30: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 30

• I We’re now going to use the Step into icon, illustrated here, that can be found on the top toolbar.

• Click this icon and the debugger will execute the current line of code and move to the next line, in this case our function. We’ll look more fully at stepping through code and examining the contents of variables shortly.

• Finally, let’s look at a third way of opening the debugger, which is probably the easiest and most useful.

• Imagine we want to stop our code’s execution and open the debugger just before the for loop is executed. We can do this by simply adding the keyword debugger to our script, which will stop the execution at that point and open the debugger Let’s do that now

.• We need to close the debugger, return to our text editor, and add the

debugger code to the script, see next slide.

Page 31: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 31

• Now refresh the page in Internet Explorer, and we’ll find that the debugger opens, with code execution paused on the line with the debugger keyword in it.

Page 32: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 32

Stepping Through Code

• There are three important ways of stepping through code, each involving one of the icons from the top toolbar of the script debugger

d-= We may find that having stepped into a function we get half way through and decide the function is not the source of the bug and we want to execute the remaining lines of code in the function, thencontinue step-by-step from the point at which the function was called. This is called stepping out of the function, and uses the Step Out icon.

L There may also be times when we have some code with a bug in it that calls a number of functions.If we know that some of the functions are bug free, then we may want to just execute them and not actually step into them and see them being executed line by line. For this the debugger has the Step Over icon, which executes the code within a function but without us having to go through it line by line.

Page 33: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 33

• Let’s alter our times table code in debug_timeatable htm and demonstrate the three methods of stepping action. Note that the debugger keyword has been removed from inside the writeTimesTable() function and is now in the second script block.

Page 34: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 34

• Save this as debug_timestable. htm. When we load this into our browser, the script debugger will be opened by the debugger statement, as shown in next slide

• Click the Step into icon and code execution will move to the next statement. in this case, the next statement is the first statement in the for loop where we initialize the variable timesTable to the value of 1, as shown in next slide.

• When we click the Step into icon again, the timesTable=1 statement is executed and we step to the next statement due to be executed, which is the condition part of the for loop. With timesTable set to 1, we know that the condition timesTable <= 12 is going to be true.

• Click the Step Into icon and the condition executes and indeed we find we’re right, the condition is true and the first statement inside the for loop, document.write(“<P> “), is next up for execution

Page 35: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 35

Page 36: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 36

• When we click the Step into icon again it will take us to the first calling of our writeTimesTable () function. We want to see what’s happening inside that function, so click Step Into again and we’ll step into the function. Our screen should look like

Page 37: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 37

• The next statement to be executed is not the var counter; or var writestring; lines, but instead the for loop’s initialization condition. The first two lines have been executed, but the script debugger does not allow us to step variable declarations line by line.

• Click the Step into icon a few times and to get the gist of the flow of execution of the function. in fact, stepping through code line by line can get a little tedious. So let’s imagine we’re happy with this function and want to run the rest of the function. Start single-stepping from the next line after the function was called. To do this, click the Step Out icon, which we discussed previously.

• Now the function has been fully executed, and we’re back out of it and at the next line, document.write(“</P>”),as we can see from next Figure.

Page 38: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 38

• Click the Step Over icon and the function will be executed, but without us having to step through it statement by statement. We should find ourselves back at the document write (“ </ P>”) line.

• If we’ve finished debugging, we can run the rest of the code without stepping through each line. by clicking the Run icon on the toolbar, which we illustrate here.

Page 39: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 39

Breakpoints

• Breakpoints are markers we can set in the debugger that force code execution to stop at that point and start single-stepping through the code.

• To set the breakpoint, we need to scroll up the code window in the debugger until we can see the line on which we want to put the breakpoint. Click that line; then click the Toggle Breakpoint icon on the toolbar, illustrated here.

• Any line with a breakpoint on it is indicated by the reddish-brown dot on the left of the code window and by the line itself being set to a reddish brown, although the line may not always be colored. We can set as many or few breakpoints at one time as we wish, so if we want to break on other lines we can add breakpoints there too.

Page 40: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 40

• To unset a breakpoint we just click the relevant line of code and click the Toggle Breakpoint icon again, and that toggles it off. To clear all breakpoints at once we can click the Clear All Breakpoints

Icon

• We find that code resumes executing without single-stepping until it reaches our breakpoint, at which point it stops. We can either single-step using the Step into icon or click the Run icon again, in which case execution continues unless a breakpoint is reached again.

Page 41: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 41

Command Window

• While stepping through code and checking that its flow of execution is useful, what would be really useful is the ability to check the values contained inside variables, evaluate conditions, and even change things on the fly. We can do all of these things using the debugger’s command window.

• Lets see if the debugger open with execution halted at the breakpoint we set previously. The line was

• Let’s see how we can find out the value currently contained in the variable writeString.

• First we need to open the command window from within the debugger. We do this by clicking the Command Window icon, illustrated here, or by selecting Command Window from the View menu.

Page 42: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 42

• In the command window, type the name of the variable we want to examine, in this case writeString; then click Enter. This will cause the value contained in the variable to be printed below our command in the command window, as shown in bellow.

Page 43: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 43

• If we want to change a variable, we can write a line of JavaScript into the command window and press Enter.

• For example, type the following into the command window and click Enter.

• Now remove the breakpoint (see the previous instructions for how to do this) and click the Run icon. if we switch to the browser, we see the results of our actions: Where the 1*1 times table result should be, the text we changed on the fly has been inserted. Note that this does not change our actual HTML source file, just the page currently loaded in the browser.

• The command window can also evaluate conditions. Refresh the browser to reset the debugger and leave execution stopped at our debugger statement. Click the Step into icon twice and execution will stop on the condition in the for statement.

Page 44: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 44

• Type the following into the command window and press Enter.

• Because this is the first time the loop has been run, timesTable is equal to 1 and so the condition timesTable <= 12 evaluates to true. Note that the debugger sometimes represents true by the value -1 and false by the value 0, so we may see the value -1 instead of true.

Page 45: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 45

• We can also use the command window to access properties of the browser’s Browser Object Model (BOM). For example, if we type window, location. href into the command window and press Enter, it will tell us where the current page is stored.

Page 46: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 46

Call Stack Window

• When single-stepping through the code, the call stack window keeps a running list of which functions have been called to get to the current point of execution in the code.

• Let’s create an example web page that demonstrates the call stack very nicely.

• Save this page as debug_calls tack. htm, and then load it into IE. When loaded, all we’ll see is a blank web page with a button. Click the button and the debugger will be opened at the debugger statement in the button1_onclick () function, which is connected to the button’s onclick event handler.

• To open the call stack window, click the Call Stack icon in the toolbar, illustrated here, or choose Call Stack from the View menu.

Page 47: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 47

Page 48: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 48

• Our debugger now looks like .

Page 49: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 49

• Every time a function is called, the debugger adds the function to the top of the call stack. We can already see that the first function called was actually the code attached to the onclick event handler of our button. The anonymous function is the event handler code that calls our onclick function. Next, added to the call stack is the function called by the onclick event, which is the function button1_onclick () shown at the top of the call stack.

• If we want to see where each function was first entered, we just need to double-click the function name in the call stack window. Double-click <Jscript> - Jscript - anonymous function and the calling line, that is, the code connected to the onclick attribute of the <input> tag, will be shown. Now double-click the top line <Jscript> -button1_onclick and that will take us back to the current execution point.

• Now single-step twice, using the Step into icon. The first step is to the line that calls the firstCall () function. The second step takes us into that function itself. The function is immediately added to the call stack

Page 50: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 50

• Click the Step into icon again and we’ll step into the second function, secondcall () . Again this is added to the call stack. One more click takes us into the third function, thirdcall (),again with its name being added to the top of the call stack.

• Now click Step into again and as we leave the function thirdcall (),we see that its name is removed from the top of the call stack. Another click takes us out of the second function secondcall() whose name is also now removed from the stack.

• Each additional click takes us out of a function, with its name removed from the call stack, until eventually all code has been executed and we’re back to the browser again.

Page 51: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 51

Page 52: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 52

Running Documents Window

• The final window we’ll look at is the running documents window. This window lists each instance of internet Explorer running and which pages, or documents, are currently loaded in that instance of IE.

• Let’s create some example pages demonstrating the use of the running documents window. The running documents window proves most useful with frame-based pages, so let’s create a page with two frames inside it.

• This first page defines the frameset. Save it as debug_frameset.htm.

Page 53: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 53

• Save this page as debug_topFrame.htm.

Page 54: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 54

• Save this page as debug_bottomFrame .htm.

• Now load debug_frameset htm into the browser You will see two frames, each containing a button.

Page 55: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 55

• I We can view all the pages currently loaded in the frames by first opening the debugger by choosing Script debuggerOpen from the View menu. Now with the debugger open we need to view the

• Running documents window by clicking the Running Documents icon in the toolbar, illustrated here, or selecting Running Documents from the View menu.

• This will initially show each instance of Internet Explorer running on the machine. Click the plus sign (+) to open a window that shows which pages are currently loaded, or running, in that instance of internet Explorer When pages are in framesets, as ours are, then pages contained within the window frameset page are included, indented underneath the frameset page. We’ll need to click the plus sign again to open them.

Page 56: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 56

• The easiest way to debug the code within the top frame is to right-click debug_topFrame htm in the Running Documents window and select Break at Next Statement. Then click the button in the top frame and the debugger will open, with execution stopped at the first statement due to be executed

(onclick= return buttonl_onclick())

• That concludes our brief tour of the Microsoft script debugger This debugger is excellent for debugging pages so that they will work in IE. However, it won’t help us spot errors due to cross-browser incompatibility. For example, what works in NN might throw an error in IE, and a page that we’ve debugged successfully in IE could easily throw an error in NN. Aside from this problem, the debugger is a great help for spotting logic errors in our code.

Page 57: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 57

Page 58: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 58

Error Handling

• When writing our programs, we want to be informed of every error. However when we’ve finally deployed the code to a web server for the whole world to access, the last thing we want the user to be seeing is a lot of error message dialog boxes. Of course, writing bug-free code would be a good start, but keep the following points in mind:

• Occasions arise when conditions beyond our control lead to errors. A good example of this is when we are relying on something, such as a Java applet, which isn’t on the user’s computer and where there is no way of checking for its existence.

• Murphy’s Law states that anything that can go wrong will go wrong!

Page 59: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 59

Preventing Errors

• The best way to handle errors is to stop them from occurring in the first place. That seems like stating the obvious, but there are a number of things we should do if we want error-free pages.

1. Check pages thoroughly on as many different platforms and browsers as possible. I realize this is easier said than done given the number of possible variations and that it’s easier when it’s a professional website created by a team of people with the hardware, software, and time to check platform and browser compatibility. The alternative is for us to decide which browsers and platforms are supported and state these requirements on our first web page. Then check that it works with the specified combinations. Use the browser and platform checking code we saw earlier in the book to send unsupported users to a nice safe and probably boring web page with reduced functionality, or maybe just supply them with a message that their browser/platform is not supported.

Page 60: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 60

2. Validate our data. if there is a way users can enter dud data that will cause our program to fall over, then they will. As a poster on the wall of somewhere 1 worked once said, “Users are idiots. Never underestimate the cunning of an idiot.” if our code will fall over if a text box is empty, we must check that it has something in it. if we need a whole number, we must check that that’s what the user has entered. is the date the user just entered valid? is the e-mail address mind your own business!! the user just entered likely to be valid? No, so we must check that it is in the format something@something. something.

• IE 5+ and Netscape 6+ include something called the try. . . catch statement. This allows us to try to run our code; if it fails, the error is caught by the catch clause and can be dealt with as we wish.

Page 61: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 61

The try...catch Statements

• The try. . . catch statements work as a pair; we can’t have one without the other.

• We use the try statement to define a block of code that we want to try to execute.

• We use the catch statement to define a block of code that will execute if an exception to the normal running of the code occurs in the block of code defined by the try statement. The term exception is key here: it means a circumstance that is extraordinary and unpredictable. Compare that with an error, which is something in the code that has been written incorrectly, if no exception occurs, the code inside the catch statement is never executed. The catch statement also enables us to get the contents of the exception message that would have been shown to the user had we not caught it first.

• Let’s create a simple example of a try. . . catch clause.

Page 62: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 62

• Save this as TryCatch. htm

Page 63: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 63

• First we define the try statement; we mark out which block of code is within the try statement by enclosing it in curly braces. Next comes the catch statement. We’ve included exception in parentheses right after the catch statement. This exception is simply a variable name. it will store an Exception object containing information about any exception thrown during execution of code inside the try code block. Although we’ve used exception, we could use any valid variable name. For example, catch (exceptionObject) would be fine and certainly more descriptive.

• The Exception object contains two properties that provide information about the exception that occurred. The bad news is that while both IF 5 and NN 6 support the Exception object and both have two properties, the names of these properties differ.

• IE’s version of the Exception object has the number and description properties. The number property is a unique number for that error type. The description property is the error message the user would normally see.

• Within the curly braces after the catch statement is the code block that will execute if and only if an error occurs, in this case, the code within the try code block is fine, and so the alert method inside the catch block won’t execute. Look at the following Example

Page 64: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 64

• Now when we load the page the first alert () method, the try block of code, will execute fine and the alert box will be displayed to the user. However, the second ablert () statement will cause an error and code execution will start at the first statement in the catch block.

• Because the IE 5 and NN 6 Exception objects support different properties, we need different code for each. How do we tell whether the browser is IE or NN?

Page 65: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 65

• By checking to see whether the exception, description property is

null, we can tell whether the description property is supported, and therefore whether the browser is one of those supporting the property such as IE. if it is equal to null, the property is not supported by the browser, so we need to display the message property of the Exception object instead, if it is not null, the description property has a value and therefore does exist and can be used.

• If you’re using internet Explorer 5.0+, the error description displayed will be “Object expected.” if you’re using Netscape Navigator 6, the same error is interpreted differently and reported as “ablert is not defined.”

• If we change the code again, so it has a different error, we’ll see something important.

Page 66: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 66

• If we were to load this code into an IF 5 or NN 6 browser, instead of the error being handled by our catch clause, we get the normal browser error message telling us “Expected ‘)‘.“

• The reason for this is that this is a syntax error; the functions and methods are valid, but we have an invalid character. The single quote in the word won’ t has ended the string parameter being passed to the alert () method. At that point JavaScript syntax, or language rules, specifies that a closing parenthesis should appear, which is not the case here. Before executing any code, JavaScript goes through all the code and checks for syntax errors, or code that breaches JavaScript’s rules. if a syntax error is found, the browser deals with it as normal; our try clause never runs and therefore cannot handle syntax errors.

Page 67: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 67

Throwing Errors

• The throw statement can be used within a try block of code to create our own run-time errors. Why create a statement to generate errors, when a bit of bad coding will do the same?

• Throwing errors can be very useful for indicating problems such as invalid user input. Rather than lots of if. . . else statements, we can check the validity of user input, then use throw to stop code execution in its tracks and cause the error catching code in the catch block of code to take over in the catch clause, we can determine whether the error is user input based, in which case we can notify the user what went wrong and how to correct it. Alternatively, if it’s an unexpected error, we can handle it more gracefully than lots of JavaScript errors.

• To use throw, we type throw and include the error message after it.

• Remember that when we catch the Exception object in the catch statement, we can get hold of the error message that we have thrown. Although we have used a string in my throw statement, we can actually throw any type of data, such as numbers and objects.

Page 68: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 68

• In this example we’ll be creating a simple factorial calculator. The important parts of this example are the try. . . catch clause and the throw statements. it’s a frameset page to enable us to demonstrate that things can go wrong that we can’t do anything about.

• In this case, the page relies on a function defined within a frameset page, so if the page is loaded on its own, a problem will occur.

• First let’s create the page that will define the frameset and also contains an important function.

Page 69: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 69

• Save this page as CalcFactorialTopFrame.htm.

Page 70: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 70

Page 71: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 71

• Save the page as CalcFactorial.htm. Then load the first page, CalcFactorialTopFrame .htm, into your browser Remember that this works only with IE5 and later and NN 6 and later and Opera 6/7.

Page 72: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 72

• If we clear the first text box and click Calculate Factorial, we’ll be told that a value needs to be entered. If we enter an invalid non-numeric value into the first text box, we’ll be told to enter a valid value, If we enter a negative value, we’ll be told to enter a positive value.

• Also, if we try loading the page CalcFactorial.htm into our browser and enter a value in the text box and click Calculate Factorial, we’ll be told that the page is not loaded into the correct frameset.

• As we’ll see, all of these error messages are created using the try. . catch and throw statements.

Page 73: Sahar Mosleh PageCalifornia State University San Marcos 1 Common Mistakes, Debugging, and Error Handling

Sahar Mosleh PageCalifornia State University San Marcos 73

Finally Clauses

• The try. catch statement has a finally clause that defines a block of script that will execute whether or not an exception was thrown. The finally clause can’t appear on its own; it must be after a try block, which the following code demonstrates.

• The finally part is a good place to put any clean-up code that needs to be executed regardless of any errors that occurred previously.