Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Exception not working

Tags:

javascript

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>
like image 673
Anthony Avatar asked Jan 24 '26 21:01

Anthony


1 Answers

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

like image 137
bfavaretto Avatar answered Jan 27 '26 10:01

bfavaretto