2

I'm trying to figure out why my code does not throw and display the error message (page is just blank) after I call it with the following statement:

document.write(add(10,wrong_input));

program.js

var add = function (a,b){
    if(typeof a !== 'number' || typeof b !== 'number'){
        throw{
            name: 'TypeError',
            message: 'add needs numbers'
        } catch(e){
            document.writeln(e.name + ': ' + e.message);
        }
    }
    return a + b;
}

program.html

<html>
    <body>
    <pre><script src="program.js"></script></pre>
    <div></div>
    </body>
</html>
3
  • 1
    Where are you looking for the error message? Commented Mar 26, 2013 at 20:23
  • 9
    You're mixing throw and try. Commented Mar 26, 2013 at 20:23
  • I'm looking for it to be display in the browser Commented Mar 26, 2013 at 20:23

3 Answers 3

6

The throw statement doesn't have a catch clause, try does. You should throw and catch separately. For example:

var add = function (a,b){
    if(typeof a !== 'number' || typeof b !== 'number'){
        throw{
            name: 'TypeError',
            message: 'add needs numbers'
        }
    }
    return a + b;
}

try {
    add('foo', 1);
} catch(ex) {
    alert(ex.message);
}

Note that I replaced document.writeln with alert, because the former will overwrite the whole document if it runs after page load. If you want something better looking, manipulate the DOM directly (by changing some element's innerHTML, appending a node, etc).

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

Comments

2

Your error handling code is slightly off, you can't throw an error and then try and write it out. You either do:

if(typeof a !== 'number' || typeof b !== 'number'){
    document.write("TypeError" + ": " + "add needs numbers");
}

Or simply just throw it:

if(typeof a !== 'number' || typeof b !== 'number'){
    throw {
        message: "add needs numbers",
        name: "TypeError"
    }
}

Then do your try catch in your function call. Personally though, I'd say stick with the first.

Comments

1

AS commented by bfaretto, You are mixing throw and try.

throw throws a exception that you define, but you are using it as a try..catch block. Here is how you could use throw and try..catch together.

var add = function (a,b){
    try {
       if(typeof a !== 'number' || typeof b !== 'number'){
            var n = {
                name: 'TypeError',
                message: 'add needs numbers'
            };
            throw n;
        }
        // throws an exception with a numeric value
    } catch (e) {
       console.log(e.name);
    }
} 

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.