When should you use try/catch in JavaScript?

后端 未结 7 920
旧时难觅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:41

    I found this from a post here:

    When Should You Use try-catch?

    The try-catch statement should be used any time you want to hide errors from the user, or any time you want to produce custom errors for your users’ benefit. If you haven’t figured it out yet, when you execute a try-catch statement, the browser’s usual error handling mechanism will be disabled.

    You can probably see the possible benefits to this when building large applications. Debugging every possible circumstance in any application’s flow is often time consuming, and many possibilities could be inadvertantly overlooked. Of course, with proper bug testing, no area should be overlooked. But the try-catch statement works as a nice fallback in areas of your code that could fail under unusual circumstances that were not foreseen during development.

    Another benefit provided by the try-catch statement is that it hides overly-technical error messages from users who wouldn’t understand them anyhow.

    The best time to use try-catch is in portions of your code where you suspect errors will occur that are beyond your control, for whatever reasons.

    When Should try-catch be Avoided?

    You shouldn’t use the try-catch statement if you know an error is going to occur, because in this case you would want to debug the problem, not mask it. The try-catch statement should be executed only on sections of code where you suspect errors might occur, and due to the overwhelming number of possible circumstances, you cannot completely verify if an error will take place, or when it will do so. In the latter case, it would be appropriate to use try-catch.

提交回复
热议问题