try: 語句測試代碼塊的錯誤,一般把可能會出錯的代碼放到這里
catch: 只有try里面的代碼塊發生錯誤時,才會執行這里的代碼,參數err記錄着try里面代碼的錯誤信息
finally: 無論有無異常里面代碼都會執行
1 try{ 2 console.log(0); 3 }catch (err){ 4 console.log(1); 5 console.log(hello); 6 }finally { 7 console.log(2); 8 } 9 //最后結果分別打印出 0 2 10 11 12 /* 13 try{ 14 a.b.c(); 15 }catch (e){ 16 console.log(1); 17 console.log(hello); 18 }finally { 19 console.log(2); 20 } 21 */ 22 //最后結果分別打印出 1 2 報錯:hello is not defined 23 24 25 26 /* 27 try{ 28 a.b.c(); 29 }catch (e){ 30 console.log(1); 31 try{ 32 console.log(hello); 33 }catch (e){ 34 console.log(3); 35 } 36 }finally { 37 console.log(2); 38 console.log(word); 39 } 40 */ 41 //最后結果分別打印出 1 3 2 報錯:word is not defined 42 43 44 45 /* 46 try{ 47 a.b.c(); 48 }catch (e){ 49 console.log(1); 50 console.log(hello); 51 }finally { 52 console.log(2); 53 console.log(word); 54 }*/ 55 //最后結果分別打印出 1 2 報錯:word is not defined
總結:
try里面的代碼報錯的時候,catch里面的代碼才會執行,finally里面的代碼永遠會執行
catch和finally里面,正常的代碼會從上到下順序執行
如果只是catch里面代碼出錯,則報catch里面的錯誤
如果catch和finally都出錯則會報finally里面的錯誤
