ref – https://stackoverflow.com/questions/7148019/when-should-you-use-try-catch-in-javascript
When a single, unconditional catch clause is used, the catch block is entered when any exception is thrown. For example, when the exception occurs in the following code, control transfers to the catch clause.
1 2 3 4 5 6 7 |
try { throw 'myException'; // generates an exception } catch (e) { // statements to handle any exceptions logMyErrors(e); // pass exception object to error handler } |
The catch block specifies an identifier (e in the example above) that holds the value specified by the throw statement. The catch block is unique in that JavaScript creates this identifier when the catch block is entered and it adds it to the current scope; the identifier lasts only for the duration of the catch block; after the catch block finishes executing, the identifier is no longer available.
finally
1 2 3 4 5 6 7 8 |
openMyFile(); try { // tie up a resource writeMyFile(theData); } finally { closeMyFile(); // always close the resource } |
Note that the finally clause executes regardless of whether an exception is thrown. Also, if an exception is thrown, the statements in the finally clause execute even if no catch clause handles the exception.
You can use the finally clause to make your script fail gracefully when an exception occurs; for example, to do general cleanup, you may need to release a resource that your script has tied up.
General situations
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 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:
1 2 3 4 |
if (isNaN(numberVariable)) { alert('you should enter a valid number'); } |
deeply nested objects where a null can pop up at any level
1 |
var something = one.two.three.four.five; |
to perform this “get” with 100% safety one would have to write a bit of verbose code:
1 2 |
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:
1 2 3 4 |
var something; try { something = one.two.three.four.five; } catch { something = "default"; } finally { doSomething(something); } |