I have the following code that works without using throw however when I use the throw keyword it doesn’t return the appropriate message. What am I doing wrong?
Update
I am deliberately calling the function addme as opposed to addMe as I want to catch the error message.
Code – That works without using throw
function addMe() {
var a = 1;
var b = 2;
return a+b;
}
try {
addme();
}
catch (err) {
document.write(err.name + " " + err.message);
}
Code – That does not work
function addMe() {
var a = 1;
var b = 2;
return a+b;
}
try {
addme();
throw "error 1";
}
catch(err) {
if(err == "error 1") {
document.write("This is a custom message for error 1");
}
}
addmeis undefined, so you never reach yourthrowstatement. (Specifically, aReferenceErroris thrown first when you calladdmerather thanaddMe)The key thing to remember is the program is read from the top down – until you inject a
GOTO(an error, calling a function, returning from a function, etc.) that sends you somewhere else. Once youGOTO Raptorthe lines beneath that line are not guaranteed to be called.To deal with any type of error you can check
err instanceof TYPE_OF_ERROR:(And please remember, a string is not an error)