It seems like with other languages that support Try/Catch, developers make use of that feature more than they do in JavaScript. Is there a reason for this? Is the JS implementation of Try/Catch flawed?
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.
Without a try catch, you run the risk of encountering unhandled exceptions. Try catch statements aren't free in that they come with performance overhead. Like any language feature, try catches can be overused.
As a conclusion, using try-catch in the case where error is never thrown seems to be as efficient as checking any simple condition. If the condition has anything more complex, try-catch is significantly faster.
A try / catch block is basically used to handle errors in JavaScript. You use this when you don't want an error in your script to break your code.
Try taking a look at this article: http://dev.opera.com/articles/view/efficient-javascript/?page=2#trycatch
From the above link:
The try-catch-finally construct is fairly unique. Unlike other constructs, it creates a new variable in the current scope at runtime. This happens each time the catch clause is executed, where the caught exception object is assigned to a variable. This variable does not exist inside other parts of the script even inside the same scope. It is created at the start of the catch clause, then destroyed at the end of it.
Because this variable is created and destroyed at runtime, and represents a special case in the language, some browsers do not handle it very efficiently, and placing a catch handler inside a performance critical loop may cause performance problems when exceptions are caught.
You can also view a similar question here
UPDATE
Adding a link to: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers as it contains useful information regarding V8 and how it handles these (and similar) constructs.
In particular:
Currently not optimizable:
Likely never optimizable:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With