HTML and CSS Reference
In-Depth Information
In this code, a custom object to represent a ball is created. It has a draw method that
expects a canvas context to draw itself on. However, if the coordinates for the ball aren't
initialized, the ball object throws a custom error. The calling code has a try…catch block so
that it can handle any unexpected errors. In this example, the consumer of the ball object
would get a meaningful message that the x-coordinate needs to be set to something valid.
A new object, Error , is used here to create the exception. The Error object constructor takes
two parameters, in this order: the error number followed by an error description. This infor-
mation should be as specific as possible to provide as much detail as possible to the calling
Checking for null values
One way to prevent many errors is to check for null values before using something. A null
value in a JavaScript program is what a variable equals before it's initialized. JavaScript knows
about the variable's existence but doesn't yet have a value.
A common place to ensure that variables have values is in functions that accept param-
eters. Consider the following function:
window.onload = function () {
try {
var a, b, c;
a = 5;
b = 10;
var result = multiplyNumbers(a, b, c);
} catch (e) {
function multiplyNumbers(first, second, third) {
if (first == null || second == null || third == null)
throw new Error(5, "Forgot to initialize a number.");
return first * second * third;
In this code, the developer forgot to initialize the variable c , resulting in a null value. In the
multiplyNumbers method, the parameters are evaluated for a null value and, if found, an error
is thrown. If this method didn't check for null values and assumed that every developer call-
ing it would never make a mistake, the results would be unexpected to the consumer of the
method. In this case, the result would be NaN (not a number), a special JavaScript type. This is
because of the attempt to perform a mathematical operation against a null value.
Search WWH ::

Custom Search