tags:

views:

39

answers:

1

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?

+4  A: 

It is because your try_it() is not returning a value, while your add() is.

Try something like this:

var try_it = function (a, b) {
    var result;  // storage for the result of add()
    try {
        result = add(a, b); // store the value that was returned from add()
    } catch (e) {
        document.writeln(e.name + ': ' + e.message);
    }
    return result;   // return the result
}

This will return the result of the add(). You were getting undefined because 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.

patrick dw
Here's an example of what Patrick said: http://jsfiddle.net/2c2nt/
Tudorizer