2016-12-22 59 views
1

它已經有一段時間,我寫javascript,我從來沒有用過try catch。我更喜歡其他的。當你使用try catch和爲什麼比簡單的else else語句更有用嗎?我從來沒有使用嘗試趕上在JavaScript

+0

如果代碼可能給出任何錯誤,您應該使用try catch。 –

+0

[try catch](http://www.w3schools.com/js/js_errors.asp) –

回答

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