Inside JavaScript

You also can throw exceptions yourself, using the throw statement:

throw expression

Like the try and catch statements, the throw statement is relatively recent, as you see in Table 3.19.

Table 3.19. The throw Statement

Statement

NS2

NS3

NS4

NS6

IE3a

IE3b

IE4

IE5

IE5.5

IE6

throw

     

x

     

x

x

x

Here's an example. Suppose you bite into a pickle , but that you can't stand pickles. In that case, you could throw a bad taste exception like this:

<HTML> <HEAD> <TITLE> Throwing an Exception </TITLE> </HEAD> <BODY> <H1>Throwing an Exception</H1> <SCRIPT LANGUAGE="JavaScript"> <!-- try { throw "Bad Taste Exception" } catch (e){ document.write("An error occurred: " + e) } // --> </SCRIPT> </BODY> </HTML>

This throws the simple text string "Bad Taste Exception" as an exception, and that string is passed to the catch statement, where the code displays it. However, the more standard way to do this is to create an Error object, throw that object, and use the object's message property in a catch statement to find out what error occurred:

(Listing 03-23.html on the web site)

<HTML> <HEAD> <TITLE> Throwing an Exception </TITLE> </HEAD> <BODY> <H1>Throwing an Exception</H1> <SCRIPT LANGUAGE="JavaScript"> <!-- try { throw Error("Bad Taste Exception") } catch (e){ document.write("An error occurred: " + e.message) } // --> </SCRIPT> </BODY> </HTML>

Figure 3.19 shows the results of this code.

Figure 3.19. Throwing a custom exception.

Here's something else you should know about exceptions: You can rethrow an exception, using the throw statement. You can nest try catch statements, for instance, and if you don't want to handle an exception in an inner try catch pair of statements, you can throw it so that it'll be handled by the outer try catch statements. Here's an example showing how this works; in this case, the inner catch statement will handle EvalError and RangeError errorsbut will throw other exceptions. The thrown exception is then caught by the outer, more general catch statement:

(Listing 03-24.html on the web site)

<HTML> <HEAD> <TITLE> Handling Specific Errors </TITLE> </HEAD> <BODY> <H1>Handling Specific Errors</H1> <SCRIPT LANGUAGE="JavaScript"> <!-- try { try { var myData = undefinedVariable } catch (e){ switch (e.name){ case "EvalError": document.write("An EvalError error occurred.") break case "RangeError": document.write("A RangeError error occurred.") break default: throw e } } } catch (e) { document.write("An error occurred: " + e.name) } // --> </SCRIPT> </BODY> </HTML>

That completes our chapter on loops , functions, and handling errors. Now we have enough JavaScript under our belts to start working with what JavaScript was designed for in the first place: the browser environment.

Категории