javascript中的try catch異常捕獲機制
1.跟java一樣,javascript也具有try catch塊,進行異常捕獲的機制。
(1)典型的try catch語句
try{
}
catch{
}
finally{
}
跟java中一樣,JS中最為典型的try catch語句也同樣分為了三個部分,try用於捕獲異常,catch用於處理異
常,而finally用於關閉資源等後續操作。
舉例:try{
throw "error"
}
catch(ex)
{
console.log(ex);
}
finally{
console.log("finally")
}
控制檯依次輸出:error,finally
(2)try,catch塊中,catch塊和finally塊只需要其一即可,因此如下的try catch塊也是可以實現的
舉例:
try {
throw "error"
}
finally{
}
只丟擲異常,其他情況不一一舉例
(3)try catch塊中包含了try catch塊
try{
try{
throw "error"
}
finally{
console.log("finally1")
}
}
catch(ex)
{
console.log(ex)
}
finally{
console.log("finally2")
}
如果是像這樣的巢狀迴圈,那麼輸出的順序為:finally1,error,finally2
(4)巢狀try catch塊中,丟擲異常
try{
try{
throw "error1"
}
catch(ex)
{
console.log(ex);
throw "error2"
}
finally{
console.log( "finally1")
}
}
catch(ex)
{
console.log(ex);
}
finally{
console.log("finally2")
}
最終的輸出為:error1,finally1,error2,finally2