Вопрос

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

Это было полезно?

Решение

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.

Другие советы

You friends are:

  • Chrome's Developer Tools: All kinds of tools are packed together.

    • Open Developer Tools by F12, Ctrl + Shift + I on Windows or Cmd + Opt + I on Mac
  • console.log: debug at runtime.

  • jshint: check syntax / misspelled variables / unused codes / unused variables / ... before run.

try / catch is very dangerous approach unless you do some logging inside catch because it will hide all errors, not fix them. Besides, it will make your code run slow.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top