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+") = " + Math.sqrt(x);
} catch(err){
return err.message;
}
}
function writeIt(){
console.log(sqrRoot("four"));
console.log(sqrRoot(""));
console.log(sqrRoot("4"));
console.log(sqrRoot("-4"));
}
writeIt();
The following is the console output, showing the different errors that are thrown, based on input to the sqrRoot()
function:
Can't Square Root Strings
Can't Square Root Nothing
sqrt(4) = 2
Sorry No Imagination