Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of try-catch in JavaScript

How time-intensive is the use of try/catch in JavaScript? I have an application and I am using it in a function which is called a few hundred times. Now I am afraid, that the try/catch statement is taking too much time and the application will take a lot longer than without it.

like image 868
Stefan Avatar asked Mar 10 '11 13:03

Stefan


People also ask

What is try catch used for?

Try/catch blocks allow a program to handle an exception gracefully in the way the programmer wants them to. For example, try/catch blocks will let a program print an error message (rather than simply crash) if it can't find an input file. Try blocks are the first part of try/catch blocks.

Is try catch good 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.

What is the use of try without catch?

Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System. exit() it will execute always.


1 Answers

There are some nice tests on jsPref:

  • http://jsperf.com/try-catch-performance-overhead
  • http://jsperf.com/try-catch-versus-massive-if
  • http://jsperf.com/try-catch-002

Conclusion: on the major browser, null to minimal differences.

like image 110
jerone Avatar answered Sep 22 '22 10:09

jerone