Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what should i use try and catch block or onerror event

I am new to javascript.Sometimes the error comes in the program but after reviewing it so many times the mistake is still unsolved.Tough the mistakes are too small to get in the sight .so to get away from this shall i use the event onError or the try catch block .Which will be the good practice for doing this .

Or is there is another way to find out the mistake or error in program in less time..

please let me know..

like image 201
user2502227 Avatar asked Sep 04 '13 18:09

user2502227


1 Answers

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.

like image 102
Joseph Myers Avatar answered Sep 20 '22 11:09

Joseph Myers