Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should you use try/catch in JavaScript?

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 connection in JavaScript.

Is try/catch statement useful in JavaScript? When can I use it?

like image 648
Sanghyun Lee Avatar asked Aug 22 '11 13:08

Sanghyun Lee


People also ask

Is it good to 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.

Should you always use try catch?

No, you should not wrap all of your code in a try-catch.

Is it better to use if else or try catch?

You should use if / else to handle all cases you expect. You should not use try {} catch {} to handle everything (in most cases) because a useful Exception could be raised and you can learn about the presence of a bug from it.

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.


2 Answers

try...catch blocks are generally encourages to be used less, and this doesn't depend on the language you use.

The main reason for this is the cost of catch blocks. Also another reason is that, when you wrap many statements with a single try...catch block, in catch block you can't be sure what was exactly the main problem.

It's better to use techniques like input validation or if...else blocks to reduce the probability of an exception (error) to happen. For example, when you want to work with a number which is taken from user, instead of using try...catch, you can use:

if (isNaN(numberVariable)) {     alert('you should enter a valid number'); } 
like image 55
Saeed Neamati Avatar answered Oct 15 '22 17:10

Saeed Neamati


One scenario I find try/catch/finally useful is with deeply nested objects where a null can pop up at any level. for example, consider this:

var something = one.two.three.four.five; 

to perform this "get" with 100% safety one would have to write a bit of verbose code:

if(one && one.two && one.two.three && one.two.three.four)    something = one.two.three.four.five; 

Now imagine the variable names are realistic and longer and you quickly get a very ugly code if statement.

I tend to use try/catch/finally to simplify this when I don't care about any "else" scenarios and just want the object or not:

var something; try { something = one.two.three.four.five; } catch { something = "default"; } finally { doSomething(something); } 
like image 38
parliament Avatar answered Oct 15 '22 16:10

parliament