Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, is it expensive to use try-catch blocks even if an exception is never thrown?

Is it "slow" to use several try-catch blocks when no exceptions are thrown in any of them? My question is the same as this one, but for JavaScript.

Suppose I have 20 functions which have try-catch blocks in them and another function that calls every one of those 20 functions where none of them throw an exception. Will my code execute slower or perform much worse because of this try-catch blocks?

like image 299
cprcrack Avatar asked Nov 01 '13 13:11

cprcrack


People also ask

Are try catch blocks expensive?

There is no cost to try/catch the only cost is when an exception is thrown, and that is regardless of whatever there is a try/catch around it or not.

Are try catch blocks expensive Java?

try has almost no expense at all. Instead of doing the work of setting up the try at runtime, the code's metadata is structured at compile time such that when an exception is thrown, it now does a relatively expensive operation of walking up the stack and seeing if any try blocks exist that would catch this exception.

Should I use try catch in JavaScript?

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.

Why you should not use try catch?

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.


1 Answers

Are you doing typical CRUD UI code? Use try catches, use loops that go to 10000 for no reason sprinkled in your code, hell, use angular/ember - you will not notice any performance issue.

If you are doing low level library, physics simulations, games, server-side etc then the never throwing try-catch block wouldn't normally matter at all but the problem is that V8 didn't support it in their optimizing compiler until version 6 of the engine, so the entire containing function that syntactically contains a try catch will not be optimized. You can easily work around this though, by creating a helper function like tryCatch:

function tryCatch(fun) {     try {         return fun();     }     catch(e) {         tryCatch.errorObj.e = e;         return tryCatch.errorObj;     } } tryCatch.errorObj = {e: null};   var result = tryCatch(someFunctionThatCouldThrow); if(result === tryCatch.errorObj) {     //The function threw     var e = result.e; } else {     //result is the returned value } 

After V8 version 6 (shipped with Node 8.3 and latest Chrome), the performance of code inside try-catch is the same as that of normal code.

like image 76
Esailija Avatar answered Sep 20 '22 09:09

Esailija