18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 14<br />

Determining the type of error<br />

Despite being limited to only one catch clause per try...catch statement, you have a couple of easy<br />

ways to determine the type of error that was thrown. The first is to use the name property of the Error<br />

object:<br />

try {<br />

eval(“a ++ b”); //causes SyntaxError<br />

} catch (oException) {<br />

if (oException.name == “SyntaxError”) {<br />

alert(“Syntax Error: “ + oException.message);<br />

} else {<br />

alert(“An unexpected error occurred: “ + oException.message);<br />

}<br />

}<br />

The second way is to use the instanceof operator and use the class name of different errors:<br />

try {<br />

eval(“a ++ b”); //causes SyntaxError<br />

} catch (oException) {<br />

if (oException instanceof SyntaxError) {<br />

alert(“Syntax Error: “ + oException.message);<br />

} else {<br />

alert(“An unexpected error occurred: “ + oException.message);<br />

}<br />

}<br />

Raising exceptions<br />

426<br />

The third edition of ECMAScript also introduced the throw statement to raise exceptions purposely. The<br />

syntax is the following:<br />

throw error_object;<br />

The error_object can be a string, a number, a Boolean value, or an actual object. All the following<br />

lines are valid:<br />

throw “An error occurred.”;<br />

throw 50067;<br />

throw true;<br />

throw new Object();<br />

It is also possible to throw an actual Error object. The constructor for the Error object takes only one<br />

parameter, the error message, making it possible to do the following:<br />

throw new Error(“You tried to do something bad.”);<br />

All the other classes of Error are also available to developers:<br />

throw new SyntaxError(“I don’t like your syntax.”);<br />

throw new TypeError(“What type of variable do you take me for?”);<br />

throw new RangeError(“Sorry, you just don’t have the range.”);<br />

throw new EvalError(“That doesn’t evaluate.”);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!