Catching "NullPointerExceptions" in JavaScript

Posted by Lenni on Stack Overflow See other posts from Stack Overflow or by Lenni
Published on 2010-04-27T12:31:14Z Indexed on 2010/04/27 12:33 UTC
Read the original article Hit count: 219

Filed under:
|

I'm writing quite a bit of code in Prototype.js which returns null if a DOM-id wasn't found.

$("someId").show();

If someId doesn't exist, a method will be called on null, which halts the entire program, in effect disabling all JS effects after the error. I could just check for null before executing such a statement, but this is getting tiring.

I would like to catch an exception but I'm not sure which one its is. MDC lists the following ECMA Script error types:

* Error
* EvalError
* RangeError
* ReferenceError
* SyntaxError
* TypeError
* URIError
* DOMException
* EventException
* RangeException

Also, do browsers have a unified way of dealing with a method call on null?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about error-handling