When should you use try/catch in JavaScript?

后端 未结 7 996
旧时难觅i
旧时难觅i 2021-01-30 00:53

When I\'m developing normal web application with JavaScript, the try/catch statement is not needed usually. There\'s no checked exception, File IO or database conne

7条回答
  •  既然无缘
    2021-01-30 01:44

    try...catch blocks are generally encourages to be used less, and this doesn't depend on the language you use.

    The main reason for this is the cost of catch blocks. Also another reason is that, when you wrap many statements with a single try...catch block, in catch block you can't be sure what was exactly the main problem.

    It's better to use techniques like input validation or if...else blocks to reduce the probability of an exception (error) to happen. For example, when you want to work with a number which is taken from user, instead of using try...catch, you can use:

    if (isNaN(numberVariable))
    {
        alert('you should enter a valid number');
    }
    

提交回复
热议问题