使用 JavaScript try/catch/finally 語句 [附示例]
本教程解釋瞭如何使用 JavaScript 中的 try/catch/finally 語句來處理錯誤,並提供了一些有用的示例。
有時會出現錯誤——而不是希望應用程序因錯誤而停止執行;你想做點別的。
其他時候,錯誤是意料之外的或對應用程序的運行有害,您希望確保報告該錯誤。
嘗試/捕捉 JavaScript 中的語句讓您可以做到這一點。
嘗試/捕捉 如果遇到錯誤,將嘗試運行一段代碼並採取指定的操作,而不是默認操作(通常會停止代碼執行)。
try/catch/finally 的語法
try { // Code to be executed } catch [(exception_var)] { // Code to execute if an exception (error) is reached } finally { // Code to execute regardless of whether an exception was reached }
注意:
- 要么趕上, 或者最終塊 應該提供
- exception_var 應該是您希望用來訪問拋出的異常的變量的名稱
示例
try { thisFunctionDoesNotExist(); } catch (err) { console.error(err); // Print the error to the console. // An error of type ReferenceError: will be sent to the console as the code above tried to execute a non-existent function // Code execution will resume after the try/catch block rather than halting } finally { console.log('Finished!'); // 'Finished!' will be sent to the console regardless of whether there was an error or not }
捕捉特定的類型 異常
通過使用 instanceof 檢查它們的類型,您可以以不同的方式處理不同類型的錯誤 :
try { thisFunctionDoesNotExist(); } catch (err) { if (err instanceof ReferenceError) { console.error(err); // Print the error to the console. } else { console.log('An unexpected error occurred!'); throw err; } }
請注意,錯誤只會 如果是 ReferenceError,則輸出到控制台。否則,它會被重新拋出以使用默認的未處理異常行為進行處理——暫停執行
其他資源
關於try/catch 的 Mozilla 技術文檔
不使用 JavaScript?以下是如何使用 try/catch 在 PHP 中!