日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Try..Catch不能捕獲的錯誤有哪些?注意事項又有哪些?

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

站在用戶的角度思考問題,與客戶深入溝通,找到潤州網(wǎng)站設(shè)計與潤州網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗,讓設(shè)計與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個性化、用戶體驗好的作品,建站類型包括:成都網(wǎng)站設(shè)計、網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣、空間域名、網(wǎng)頁空間、企業(yè)郵箱。業(yè)務(wù)覆蓋潤州地區(qū)。

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

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

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

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

1.1 try

每個try塊必須與至少一個catch或finally塊,否則會拋出SyntaxError錯誤。

我們單獨使用try塊進行驗證:

 
 
 
 
  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塊拋出的錯誤。

 
 
 
 
  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 與 無效代碼

try..catch 無法捕獲無效的 JS 代碼,例如try塊中的以下代碼在語法上是錯誤的,但它不會被catch塊捕獲。

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

1.2.2 try..catch 與 異步代碼

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

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

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

 
 
 
 
  1.  ? Uncaught ReferenceError: noSuchVariable is not defined 

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

 
 
 
 
  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塊向上拋出錯誤,如下所示:

 
 
 
 
  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 而沒有 catch 塊,看看下面會發(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塊拋出錯誤后,也會執(zhí)行finally塊
  • 如果沒有catch塊,錯誤將不能被優(yōu)雅地處理,從而導(dǎo)致未捕獲的錯誤

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塊中拋出錯誤后往后的代碼不會被執(zhí)行了
  • 即使在try塊拋出錯誤之后,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語句用于引發(fā)異常。

 
 
 
 
  1. throw  
 
 
 
 
  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. 異步代碼中的錯誤處理

對于異步代碼的錯誤處理可以Promise和async await。

2.1 Promise 中的 then..catch

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

 
 
 
 
  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);  // 這里不會被執(zhí)行 
  8.   }) 
  9.   .then(res => { 
  10.       // 這里也不會執(zhí)行,因為錯誤還沒有被處理 
  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.       // 這里不會被執(zhí)行 
  22.       console.error(err); 
  23.   }) 

我們來看一個更實際的示例,其中我們使用fetch調(diào)用API,該 API 返回一個promise對象,我們使用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 (: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返回一個promise對象, 我們使用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 (:3:15) 
  3.     at :11:7 

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

3.1 Error

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

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

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

 
 
 
 
  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 :1:13 

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

3.2 EvalError

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

3.3 RangeError

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

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

3.4 ReferenceError

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

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

3.5 SyntaxError

當(dāng)你在 JS 代碼中使用任何錯誤的語法時,都會引發(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ù)期的類型,則拋出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

如果以錯誤的方式使用全局 URI 方法,則會拋出URIError。

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

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

 
 
 
 
  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 

我們還可以進一步增強CustomError對象以包含錯誤代碼

 
 
 
 
  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)載自微信公眾號「大遷世界」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系大遷世界公眾號。


本文名稱:Try..Catch不能捕獲的錯誤有哪些?注意事項又有哪些?
網(wǎng)站鏈接:http://www.dlmjj.cn/article/dpochis.html