2016-12-22 6 views
1

にトライキャッチを使用したことがない私はjavascriptを書いて、私はトライキャッチを使用したことがないしばらくしています。私は他の人が好きです。 try catchを使用したとき、なぜ単純なif 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 
関連する問題