Isn't the jquery try catch a good practice?

500    Asked by MelanieHughes in Java , Asked on Oct 11, 2022

There is a provision for try-catch block in javascript. While in java or any other language it is mandatory to have error handling, I don't see anybody using them in javascript to a greater extent. Isn't it a good practice or just we don't need them in javascript?

Answered by Melany Doi

Regarding the jquery try catch -


One should avoid throw errors as the way to pass error conditions around in applications.

The throw statement should only be used "For this should never happen, crash and burn. Do not recover elegantly in any way"

try catch however is used in situations 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



Your Answer

Interviews

Parent Categories