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>
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With