1

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?

1 Answers1

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