實(shí)例解析js中try、catch、finally的執(zhí)行規(guī)則
try: 語句測試代碼塊的錯誤,一般把可能會出錯的代碼放到這里
catch: 只有try里面的代碼塊發(fā)生錯誤時,才會執(zhí)行這里的代碼,參數(shù)err記錄著try里面代碼的錯誤信息
finally: 無論有無異常里面代碼都會執(zhí)行
try{
console.log(0);
}catch (err){
console.log(1);
console.log(hello);
}finally {
console.log(2);
}
//最后結(jié)果分別打印出 0 2
/*
try{
a.b.c();
}catch (e){
console.log(1);
console.log(hello);
}finally {
console.log(2);
}
*/
//最后結(jié)果分別打印出 1 2 報錯:hello is not defined
/*
try{
a.b.c();
}catch (e){
console.log(1);
try{
console.log(hello);
}catch (e){
console.log(3);
}
}finally {
console.log(2);
console.log(word);
}
*/
//最后結(jié)果分別打印出 1 3 2 報錯:word is not defined
/*
try{
a.b.c();
}catch (e){
console.log(1);
console.log(hello);
}finally {
console.log(2);
console.log(word);
}*/
//最后結(jié)果分別打印出 1 2 報錯:word is not defined
總結(jié):
try里面的代碼報錯的時候,catch里面的代碼才會執(zhí)行,finally里面的代碼永遠(yuǎn)會執(zhí)行
catch和finally里面,正常的代碼會從上到下順序執(zhí)行
如果只是catch里面代碼出錯,則報catch里面的錯誤
如果catch和finally都出錯則會報finally里面的錯誤
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
js數(shù)組轉(zhuǎn)json并在后臺對其解析具體實(shí)現(xiàn)
這篇文章主要介紹了js數(shù)組轉(zhuǎn)json并在后臺對其解析具體實(shí)現(xiàn),有需要的朋友可以參考一下2013-11-11
JS控制圖片翻轉(zhuǎn)示例代碼(兼容firefox,ie,chrome)
本篇文章主要介紹了JS控制圖片翻轉(zhuǎn)示例代碼(兼容firefox,ie,chrome) 需要的朋友可以過來參考下,希望對大家有所幫助2013-12-12
Bootstrap菜單按鈕及導(dǎo)航實(shí)例解析
這篇文章主要介紹了Bootstrap菜單按鈕及導(dǎo)航的相關(guān)資料,本文介紹的非常詳細(xì),具有參考借鑒價值,感興趣的朋友一起學(xué)習(xí)吧2016-09-09

