【发布时间】:2016-12-22 09:38:29
【问题描述】:
我写 javascript 已经有一段时间了,但我从未使用过 try catch。如果别的,我更喜欢。当你使用 try catch 时,为什么它比简单的 if else 语句有用?
【问题讨论】:
-
如果代码可能出现任何错误,您应该使用 try catch。
标签: javascript
我写 javascript 已经有一段时间了,但我从未使用过 try catch。如果别的,我更喜欢。当你使用 try catch 时,为什么它比简单的 if else 语句有用?
【问题讨论】:
标签: javascript
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
【讨论】: