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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.