ref –
- http://chineseruleof8.com/code/index.php/2018/06/22/try-catch/
- http://chineseruleof8.com/code/index.php/2018/06/25/throw-error/
- https://stackoverflow.com/questions/3217294/javascript-try-catch-performance-vs-error-checking-code
- https://stackoverflow.com/questions/1722964/when-to-use-try-catch-blocks
Programs must be written for people to read, and only incidentally for machines to execute
Always aim for readable code
The key thing to remember is: Avoid try-catch in performance-critical functions, and loops
Anywhere else they won’t do much harm. Use them wisely, use them sparingly. As a side note if you want to support older browsers they may not have try-catch.
The try-catch block is said to be expensive. However if critical performance is not an issue, using it is not necessarily a concern.
The penalty with try-catch blocks everywhere is:
- Readability: plumbing your code with plenty of try-catch is ugly and distracting
- inappropriate: it’s a bad idea to insert such block if your code is not subject to exception-crash. Insert it only if you expect a failure in your code.
- the try-catch block is synchronous and is not effective when it comes to async programming. During an async request you handle both the error and success events in dedicated callbacks. No need for try-catch.
The basic rule of thumb for catching exceptions is to catch exceptions if and only if you have a meaningful way of handling them.
Don’t catch an exception if you’re only going to log the exception and throw it up the stack. It serves no meaning and clutters code.
Do catch an exception when you are expecting a failure in a specific part of your code, and if you have a fallback for it.
Of course you always have the case of checked exceptions which require you to use try/catch blocks, in which case you have no other choice. Even with a checked exception, make sure you log properly and handle as cleanly as possible.
Assuming undefinedfunction() is undefined, when the browser runs it, no errors will be shown. The syntax for try/catch/finally is a try clause followed by either a catch or finally clause (at least one or both of them). The catch clause if defined traps any errors that has occurred from try, and is indirectly passed the error object that contains additional info about the error. Lets see a slightly more complex example now:
1 2 3 4 5 6 7 |
try{ undefinedfunction() alert('I guess you do exist') } catch(e){ alert('An error has occurred: '+e.message) } |
Click on the above button, and notice how only “An Error has occurred” alert pops up, but not “I guess you do exist”. This tells us that when try encounters an error, it immediately skips any remaining code inside it and goes straight to catch. The default error message is obviously suppressed, though you can still retrieve this information by accessing the Error object that gets indirectly passed into catch.