Throwing Your Own Errors
You can also throw your own errors by using a throw
statement. The following code illustrates how to add throw
statements to a function to throw an error, even if a script error does not occur. The function sqrRoot()
accepts a single argument x
. It then tests x
to verify that it is a positive
number and returns a string with the square root of x
. If x
is not a positive number, the appropriate error is thrown, and the catch
block returns the error:
function sqrRoot(x) { try { if(x=="") throw {message:"Can't Square Root Nothing"}; if(isNaN(x)) throw {message:"Can't Square Root Strings"}; if(x<0) throw {message:"Sorry No Imagination"}; return "sqrt("+x+") ...
Get Learning AngularJS now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.