Can I define custom types for user-defined exceptions in JavaScript? If I can, how would I do it?
Use the throw statement.
JavaScript doesn't differ what exception type it is like i.e. Java does. JavaScript just notices, there's an exception and where you catch it, you can "look" what the excpetion "says".
If you have different exception types you have to throw, I'd suggest use variables which contain the string/object of the exception i.e. message. Where you need it use "throw myException" and in the catch, compare the caught excpetion to myException.
Yes. You can throw anything you want: integers, strings, objects, whatever. If you want to throw an object, then simply create a new object, just as you would create one under other circumstances, and then throw it. Mozilla's Javascript reference has several examples.
You could implement your own exceptions and their handling for example like here:
// define exceptions "classes" function NotNumberException() { } function NotPositiveNumberException() { } // try some code try { // some function/code that can throw if (isNaN(value)) throw new NotNumberException; else if (value < 0) throw new NotPositiveNumberException; } catch (e) { if (e instanceof NotNumberException) { alert("not a number"); } else if (e instanceof NotPositiveNumberException) { alert("not a positive number"); } }
There is another syntax for catching a typed exception, although this won't work in every browser (for example not in IE):
// define exceptions "classes" function NotNumberException() { } function NotPositiveNumberException() { } // try some code try { // some function/code that can throw if (isNaN(value)) throw new NotNumberException; else if (value < 0) throw new NotPositiveNumberException; } catch (e if e instanceof NotNumberException) { alert("not a number"); } catch (e if e instanceof NotPositiveNumberException) { alert("not a positive number"); }
From: http://www.webreference.com/programming/javascript/rg32/2.html
throw {
name: "System Error",
level: "Show Stopper",
message: "Error detected. Please contact the system administrator.",
htmlMessage: "Error detected. Please contact the <a href="mailto:[email protected]">system administrator</a>."
}