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?
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.
No, you should not wrap all of your code in a 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.
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.
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'); }
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); }
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