2009年9月23日 星期三

[JavaScript] try/catch/finally

Reference: JavaScript - The Definitive Guide, Section 6.17

try/catch/finally 的執行示意圖:(四種情況)




另外有一段話要特別注意:
If a finally block itself transfers control with a return, continue, break, or throw statement, or by calling a method that throws an exception, the pending control transfer is abandoned, and this new transfer is processed. For example, if a finally clause throws an exception, that exception replaces any exception that was in the process of being thrown. If a finally clause issues a return statement, the method returns normally, even if an exception has been thrown and has not yet been handled.
finally 裡面用了 return/continue/break/throw 時,之前預計的 flow 會無效,改成走新的這個 flow。例如 finally 裡面有新的 exception 被丟出來時,原本就的 exception 就會不見;或者 finally 裡面有 return,那原本沒處理的 exception 也會被河蟹(XD)掉。
* 註:對於這件事情的理解是:如果有緊急狀況(exception)發生了,卻在急救(finally)時假裝沒事(return),那緊急狀況被忽略也只是剛好而已。