Anthony
Anthony

Reputation: 4050

JavaScript Exception not working

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>

Upvotes: 2

Views: 95

Answers (3)

Bertrand
Bertrand

Reputation: 13570

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);
    }
} 

Upvotes: 1

Mathew Thompson
Mathew Thompson

Reputation: 56429

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.

Upvotes: 2

bfavaretto
bfavaretto

Reputation: 71918

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).

Upvotes: 6

Related Questions