Java Reference
In-Depth Information
• The
name
property returns the name of the error constructor function used as a
string, such as
"Error"
or
"ReferenceError"
.
• The
message
property returns a description of the error and should be provided
as an argument to the
Error
constructor function.
• The
stack
property will return a stack trace for that error.
Throwing Exceptions
So far we have seen errors that are thrown automatically by the JavaScript engine when an
error occurs. It's also possible to throw your own exceptions using the
throw
statement.
This will allow for any problems in your code to be highlighted and dealt with, rather than
lurk quietly in the background.
The
throw
statement can be applied to any JavaScript value and the execution of the pro-
gram will still stop:
throw 5;
throw "JavaScript"
throw { name: "Ninja" }
It is best practice, however, to throw an
error
object. This can then be caught in a
catch
block, which is covered later in the chapter:
throw new Error("Something has gone badly wrong!"
As an example, let's write a function called
squareRoot()
to find the square root of a
number. This can be done using the
Math.sqrt()
method, but it returns
NaN
for negat-
ive arguments. This is not strictly correct (the answer should be an imaginary number, but
these are unsupported in JavaScript). Our function will throw an error if the user tries to
use a negative argument:
function squareRoot(number) {
"use strict";
if (number < 0) {
throw new Error("You can't square root negative
numbers")
