我从未在javascript中使用try catch

时间:2016-12-22 09:38:30

标签: javascript

我已经有一段时间写javascript而且我从未使用过try catch。我更喜欢别的。当你使用try catch时,为什么它比一个简单的if else语句更有用呢?

1 个答案:

答案 0 :(得分: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