自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Try..Catch 不能捕獲的錯(cuò)誤有哪些?注意事項(xiàng)又有哪些?

開(kāi)發(fā) 前端
今天的內(nèi)容中,我們來(lái)學(xué)習(xí)一下使用try、catch、finally和throw進(jìn)行錯(cuò)誤處理。我們還會(huì)講一下 JS 中內(nèi)置的錯(cuò)誤對(duì)象(Error, SyntaxError, ReferenceError等)以及如何定義自定義錯(cuò)誤。

[[373698]]

本文已經(jīng)原作者 Ashish Lahoti 授權(quán)翻譯。

今天的內(nèi)容中,我們來(lái)學(xué)習(xí)一下使用try、catch、finally和throw進(jìn)行錯(cuò)誤處理。我們還會(huì)講一下 JS 中內(nèi)置的錯(cuò)誤對(duì)象(Error, SyntaxError, ReferenceError等)以及如何定義自定義錯(cuò)誤。

1.使用 try..catch..finally..throw

在 JS 中處理錯(cuò)誤,我們主要使用try、catch、finally和throw關(guān)鍵字。

  • try塊包含我們需要檢查的代碼
  • 關(guān)鍵字throw用于拋出自定義錯(cuò)誤
  • catch塊處理捕獲的錯(cuò)誤
  • finally 塊是最終結(jié)果無(wú)論如何,都會(huì)執(zhí)行的一個(gè)塊,可以在這個(gè)塊里面做一些需要善后的事情

1.1 try

每個(gè)try塊必須與至少一個(gè)catch或finally塊,否則會(huì)拋出SyntaxError錯(cuò)誤。

我們單獨(dú)使用try塊進(jìn)行驗(yàn)證:

  1. try { 
  2.   throw new Error('Error while executing the code'); 
  1. ⓧ Uncaught SyntaxError: Missing catch or finally after try 

1.2 try..catch

建議將try與catch塊一起使用,它可以優(yōu)雅地處理try塊拋出的錯(cuò)誤。

  1. try { 
  2.   throw new Error('Error while executing the code'); 
  3. } catch (err) { 
  4.   console.error(err.message); 
  1. ➤ ⓧ Error while executing the code 

1.2.1 try..catch 與 無(wú)效代碼

try..catch 無(wú)法捕獲無(wú)效的 JS 代碼,例如try塊中的以下代碼在語(yǔ)法上是錯(cuò)誤的,但它不會(huì)被catch塊捕獲。

  1. try { 
  2.   ~!$%^&* 
  3. } catch(err) { 
  4.   console.log("這里不會(huì)被執(zhí)行"); 
  1. ➤ ⓧ Uncaught SyntaxError: Invalid or unexpected token 

1.2.2 try..catch 與 異步代碼

同樣,try..catch無(wú)法捕獲在異步代碼中引發(fā)的異常,例如setTimeout:

  1. try { 
  2.   setTimeout(function() { 
  3.     noSuchVariable;   // undefined variable 
  4.   }, 1000); 
  5. } catch (err) { 
  6.   console.log("這里不會(huì)被執(zhí)行"); 

未捕獲的ReferenceError將在1秒后引發(fā):

  1. ➤ ⓧ Uncaught ReferenceError: noSuchVariable is not defined 

所以 ,我們應(yīng)該在異步代碼內(nèi)部使用 try..catch 來(lái)處理錯(cuò)誤:

  1. setTimeout(function() { 
  2.   try { 
  3.     noSuchVariable; 
  4.   } catch(err) { 
  5.     console.log("error is caught here!"); 
  6.   } 
  7. }, 1000); 

1.2.3 嵌套 try..catch

我們還可以使用嵌套的try和catch塊向上拋出錯(cuò)誤,如下所示:

  1. try { 
  2.   try { 
  3.     throw new Error('Error while executing the inner code'); 
  4.   } catch (err) { 
  5.     throw err; 
  6.   } 
  7. } catch (err) { 
  8.   console.log("Error caught by outer block:"); 
  9.   console.error(err.message); 
  1. Error caught by outer block: 
  2. ➤ ⓧ Error while executing the code 

1.3 try..finally

不建議僅使用 try..finally 而沒(méi)有 catch 塊,看看下面會(huì)發(fā)生什么:

  1. try { 
  2.   throw new Error('Error while executing the code'); 
  3. } finally { 
  4.   console.log('finally'); 
  1. finally 
  2. ➤ ⓧ Uncaught Error: Error while executing the code 

這里注意兩件事:

  • 即使從try塊拋出錯(cuò)誤后,也會(huì)執(zhí)行finally塊
  • 如果沒(méi)有catch塊,錯(cuò)誤將不能被優(yōu)雅地處理,從而導(dǎo)致未捕獲的錯(cuò)誤

1.4 try..catch..finally

建議使用try...catch塊和可選的finally塊。

  1. try { 
  2.   console.log("Start of try block"); 
  3.   throw new Error('Error while executing the code'); 
  4.   console.log("End of try block -- never reached"); 
  5. } catch (err) { 
  6.   console.error(err.message); 
  7. } finally { 
  8.   console.log('Finally block always run'); 
  9. console.log("Code execution outside try-catch-finally block continue.."); 
  1. Start of try block 
  2. ➤ ⓧ Error while executing the code 
  3. Finally block always run 
  4. Code execution outside try-catch-finally block continue.. 

這里還要注意兩件事:

  • 在try塊中拋出錯(cuò)誤后往后的代碼不會(huì)被執(zhí)行了
  • 即使在try塊拋出錯(cuò)誤之后,finally塊仍然執(zhí)行

finally塊通常用于清理資源或關(guān)閉流,如下所示:

  1. try { 
  2.   openFile(file); 
  3.   readFile(file); 
  4. } catch (err) { 
  5.   console.error(err.message); 
  6. } finally { 
  7.   closeFile(file); 

1.5 throw

throw語(yǔ)句用于引發(fā)異常。

 

  1. throw <expression> 
  1. // throw primitives and functions 
  2. throw "Error404"
  3. throw 42; 
  4. throw true
  5. throw {toString: function() { return "I'm an object!"; } }; 
  6.  
  7. // throw error object 
  8. throw new Error('Error while executing the code'); 
  9. throw new SyntaxError('Something is wrong with the syntax'); 
  10. throw new ReferenceError('Oops..Wrong reference'); 
  11.  
  12. // throw custom error object 
  13. function ValidationError(message) { 
  14.   this.message = message; 
  15.   this.name = 'ValidationError'
  16. throw new ValidationError('Value too high'); 

2. 異步代碼中的錯(cuò)誤處理

對(duì)于異步代碼的錯(cuò)誤處理可以Promise和async await。

2.1 Promise 中的 then..catch

我們可以使用then()和catch()鏈接多個(gè) Promises,以處理鏈中單個(gè) Promise 的錯(cuò)誤,如下所示:

  1. Promise.resolve(1) 
  2.   .then(res => { 
  3.       console.log(res);  // 打印 '1' 
  4.  
  5.       throw new Error('something went wrong');  // throw error 
  6.  
  7.       return Promise.resolve(2);  // 這里不會(huì)被執(zhí)行 
  8.   }) 
  9.   .then(res => { 
  10.       // 這里也不會(huì)執(zhí)行,因?yàn)殄e(cuò)誤還沒(méi)有被處理 
  11.       console.log(res);     
  12.   }) 
  13.   .catch(err => { 
  14.       console.error(err.message);  // 打印 'something went wrong' 
  15.       return Promise.resolve(3); 
  16.   }) 
  17.   .then(res => { 
  18.       console.log(res);  // 打印 '3' 
  19.   }) 
  20.   .catch(err => { 
  21.       // 這里不會(huì)被執(zhí)行 
  22.       console.error(err); 
  23.   }) 

我們來(lái)看一個(gè)更實(shí)際的示例,其中我們使用fetch調(diào)用API,該 API 返回一個(gè)promise對(duì)象,我們使用catch塊優(yōu)雅地處理 API 失敗。

  1. function handleErrors(response) { 
  2.     if (!response.ok) { 
  3.         throw Error(response.statusText); 
  4.     } 
  5.     return response; 
  6.  
  7. fetch("http://httpstat.us/500"
  8.     .then(handleErrors) 
  9.     .then(response => console.log("ok")) 
  10.     .catch(error => console.log("Caught", error)); 
  1. Caught Error: Internal Server Error 
  2.     at handleErrors (<anonymous>:3:15) 

2.2 try..catch 和 async await

在 async await 中 使用try..catch 比較容易:

  1. (async function() { 
  2.     try { 
  3.         await fetch("http://httpstat.us/500"); 
  4.     } catch (err) { 
  5.         console.error(err.message); 
  6.     } 
  7. })(); 

讓我們看同一示例,其中我們使用fetch調(diào)用API,該API返回一個(gè)promise對(duì)象, 我們使用try..catch塊優(yōu)雅地處理API失敗。

  1. function handleErrors(response) { 
  2.     if (!response.ok) { 
  3.         throw Error(response.statusText); 
  4.     } 
  5.  
  6. (async function() { 
  7.     try { 
  8.       let response = await fetch("http://httpstat.us/500"); 
  9.       handleErrors(response); 
  10.       let data = await response.json(); 
  11.       return data; 
  12.     } catch (error) { 
  13.         console.log("Caught", error) 
  14.     } 
  15. })(); 
  1. Caught Error: Internal Server Error 
  2.     at handleErrors (<anonymous>:3:15) 
  3.     at <anonymous>:11:7 

3. JS 中的內(nèi)置錯(cuò)誤

3.1 Error

JavaScript 有內(nèi)置的錯(cuò)誤對(duì)象,它通常由try塊拋出,并在catch塊中捕獲,Error 對(duì)象包含以下屬性:

  • name:是錯(cuò)誤的名稱(chēng),例如 “Error”, “SyntaxError”, “ReferenceError” 等。
  • message:有關(guān)錯(cuò)誤詳細(xì)信息的消息。
  • stack:是用于調(diào)試目的的錯(cuò)誤的堆棧跟蹤。

我們創(chuàng)建一個(gè)Error 對(duì)象,并查看它的名稱(chēng)和消息屬性:

  1. const err = new Error('Error while executing the code'); 
  2.  
  3. console.log("name:", err.name); 
  4. console.log("message:", err.message); 
  5. console.log("stack:", err.stack); 
  1. name: Error 
  2. message: Error while executing the code 
  3. stack: Error: Error while executing the code 
  4.     at <anonymous>:1:13 

JavaScript 有以下內(nèi)置錯(cuò)誤,這些錯(cuò)誤是從 Error 對(duì)象繼承而來(lái)的

3.2 EvalError

EvalError 表示關(guān)于全局eval()函數(shù)的錯(cuò)誤,這個(gè)異常不再由 JS 拋出,它的存在是為了向后兼容。

3.3 RangeError

當(dāng)值超出范圍時(shí),將引發(fā)RangeError。

  1. ➤ [].length = -1 
  2. ⓧ Uncaught RangeError: Invalid array length 

3.4 ReferenceError

當(dāng)引用一個(gè)不存在的變量時(shí),將引發(fā) ReferenceError。

  1. ➤ x = x + 1; 
  2. ⓧ Uncaught ReferenceError: x is not defined 

3.5 SyntaxError

當(dāng)你在 JS 代碼中使用任何錯(cuò)誤的語(yǔ)法時(shí),都會(huì)引發(fā)SyntaxError。

  1. ➤ function() { return 'Hi!' } 
  2. ⓧ Uncaught SyntaxError: Function statements require a function name 
  3.  
  4. ➤ 1 = 1 
  5. ⓧ Uncaught SyntaxError: Invalid left-hand side in assignment 
  6.  
  7. ➤ JSON.parse("{ x }"); 
  8. ⓧ Uncaught SyntaxError: Unexpected token x in JSON at position 2 

3.6 TypeError

如果該值不是預(yù)期的類(lèi)型,則拋出TypeError。

  1. ➤ 1(); 
  2. ⓧ Uncaught TypeError: 1 is not a function 
  3.  
  4. ➤ null.name
  5. ⓧ Uncaught TypeError: Cannot read property 'name' of null 

3.7 URIError

如果以錯(cuò)誤的方式使用全局 URI 方法,則會(huì)拋出URIError。

  1. ➤ decodeURI("%%%"); 
  2. ⓧ Uncaught URIError: URI malformed 

4. 定義并拋出自定義錯(cuò)誤我們也可以用這種方式定義自定義錯(cuò)誤。

  1. class CustomError extends Error { 
  2.   constructor(message) { 
  3.     super(message); 
  4.     this.name = "CustomError"
  5.   }  
  6. }; 
  7.  
  8. const err = new CustomError('Custom error while executing the code'); 
  9.  
  10. console.log("name:", err.name); 
  11. console.log("message:", err.message); 
  1. name: CustomError 
  2. message: Custom error while executing the code 

我們還可以進(jìn)一步增強(qiáng)CustomError對(duì)象以包含錯(cuò)誤代碼

  1. class CustomError extends Error { 
  2.   constructor(message, code) { 
  3.     super(message); 
  4.     this.name = "CustomError"
  5.     this.code = code; 
  6.   }  
  7. }; 
  8.  
  9. const err = new CustomError('Custom error while executing the code'"ERROR_CODE"); 
  10.  
  11. console.log("name:", err.name); 
  12. console.log("message:", err.message); 
  13. console.log("code:", err.code); 
  1. name: CustomError 
  2. message: Custom error while executing the code 
  3. code: ERROR_CODE 

在try..catch塊中使用它:

  1. try{ 
  2.   try { 
  3.     null.name
  4.   }catch(err){ 
  5.     throw new CustomError(err.message, err.name);  //message, code 
  6.   } 
  7. }catch(err){ 
  8.   console.log(err.name, err.code, err.message); 

CustomError TypeError Cannot read property 'name' of null

本文轉(zhuǎn)載自微信公眾號(hào)「大遷世界」,可以通過(guò)以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系大遷世界公眾號(hào)。

 

責(zé)任編輯:武曉燕 來(lái)源: 大遷世界
相關(guān)推薦

2010-05-07 10:19:48

Oracle 注意事項(xiàng)

2020-09-27 07:48:40

不用try catch

2022-06-30 13:41:44

SQL 語(yǔ)句group by

2022-07-14 08:02:02

NPM依賴(lài)治理

2010-07-30 13:28:10

2022-03-10 23:12:12

云計(jì)算數(shù)據(jù)管理架構(gòu)

2010-07-30 10:11:05

DB2臨時(shí)表

2011-05-06 14:05:56

投影機(jī)

2011-05-26 11:22:04

SEO

2011-04-27 16:16:46

投影機(jī)

2023-09-07 07:53:21

JavaScriptGoRust

2009-12-15 17:47:17

VSIP

2019-09-25 07:39:24

移動(dòng)端PC端表單

2022-07-15 07:20:42

數(shù)字化智能運(yùn)維

2021-07-30 11:00:02

iOS蘋(píng)果系統(tǒng)

2010-11-26 16:27:01

MySQL使用變量

2023-01-14 09:49:11

2020-10-20 14:05:48

用戶需求分析IT

2011-09-26 11:02:10

2021-11-16 10:35:59

云計(jì)算云計(jì)算環(huán)境云應(yīng)用
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)