It is not necessarily good to say one is better than the other. For your situation, I do feel that onerror
is easy and appropriate, as it lets you alert the error message reported by JavaScript without needing to rewrite your code within try/catch blocks.
Demo code with the onerror
handler in a self-contained script added above the rest of the page's code, along with an example syntax error which triggers a prompt showing the JavaScript error message.
<script>
onerror = function(m) {
return confirm(
'Scripts on this page generated an error message: ' +
m +
'\n\nDo you wish to continue running the scripts?');
}
</script>
<script>
alert(' hello';
</script>
The above bad code generates an alert message 'unexpected token ;' because of the missing parenthesis.