It has been a while I write javascript and I never used try catch. I prefer if else. When you used try catch and why it's useful compared to a simple if else statement?
Asked
Active
Viewed 113 times
1
-
if the code could give any error you should use try catch. – Kevin Kloet Dec 22 '16 at 09:39
-
[try catch](http://www.w3schools.com/js/js_errors.asp) – omri_saadon Dec 22 '16 at 09:40
1 Answers
0
try catch however is used in situation where host objects or ECMAScript may throw errors.
Example:
var json
try {
json = JSON.parse(input)
} catch (e) {
// invalid json input, set to null
json = null
}
Recommendations in the node.js community is that you pass errors around in callbacks (Because errors only occur for asynchronous operations) as the first argument
fs.readFile(uri, function (err, fileData) {
if (err) {
// handle
// A. give the error to someone else
return callback(err)
// B. recover logic
return recoverElegantly(err)
// C. Crash and burn
throw err
}
// success case, handle nicely
})
There are also other issues like try / catch is really expensive and it's ugly and it simply doesn't work with asynchronous operations.
So since synchronous operations should not throw an error and it doesn't work with asynchronous operations, no-one uses try catch except for errors thrown by host objects or ECMAScript

rani
- 68
- 8