I have a non-working code. I think it needs just a little mods and it should be working. I couldn’t figure it out. Just started studying JS.
var add = function (a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw {
name: 'TypeError',
message: 'add needs numbers'
}
}
return a + b;
}
var try_it = function (a, b) {
try {
add(a, b);
} catch (e) {
document.writeln(e.name + ': ' + e.message);
}
}
document.writeln(try_it(2, 7));
It doesn’t work. I get “undefined” error. However, if I invoke function add directly…
var add = function (a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw {
name: 'TypeError',
message: 'add needs numbers'
}
}
return a + b;
}
var try_it = function (a, b) {
try {
add(a, b);
} catch (e) {
document.writeln(e.name + ': ' + e.message);
}
}
document.writeln(add(2, 7));
… I get the desired result. There must be something wrong with function try_it?
It is because your
try_it()is not returning a value, while youradd()is.Try something like this:
This will return the result of the
add(). You were gettingundefinedbecause that is a default return value when one is not specified.EDIT: Changed it to store the result in a variable instead of returning immediately. This way you can still catch an error.