在 JavaScript 中,finally 的作用是什麼?


在 JavaScript 中,finally 是一個程式碼塊或語句,在使用 try 和 catch 塊處理錯誤時,無論如何都會執行。這些 JavaScript 中的 try、catch 和 finally 塊將執行可能出錯並可能導致程式行為異常(突然終止)的程式碼。

這個 finally 塊位於 try 和 catch 塊之後,如果 try 或 catch 塊中的任何一個被執行,它都一定會被執行。finally 塊允許我們定義必須執行的操作,而不管某些程式碼成功或失敗。

  • 在 JavaScript 中進行錯誤處理時,try 塊是必須的,而 catch 和 finally 是可選的。

  • 這三個塊可以組合使用,例如 try 與 catch 和 finally 同時使用,或者 try 塊與另外兩個塊中的任何一個塊一起使用。

  • try 可以不帶任何塊使用。但是,要使用 finally,則必須使用 try 塊。

語法

這是 JavaScript 中 finally() 塊以及 try 和 catch 塊的語法:

try{
   //The code where the chances of error can be predicted 
}
catch{
   //The code which will be executed if try block is executed
}
finally{
   //The code which will be definitely executed after the try and catch blocks.
}

try 塊中提到的錯誤主要是由於一些執行時問題和程式設計師造成的錯誤。程式的執行順序如下。

首先,執行 try 塊中的程式碼,如果發生任何錯誤,則編譯器會搜尋 catch 塊,如果存在 catch 塊,則執行其中的內容。

然後,執行 finally 塊。下面將透過示例說明 finally 及其他 try 和 catch 塊的實現。

示例 1

此示例演示了 try 和 catch 同時使用時 finally 塊的執行:

<!DOCTYPE html> <html> <head> </head> <body> <h2> Finally - JavaScript</h2> <button type="button" onclick="forFinally()"> Click the button to show the result </button> <p id="try"> </p> <p id="catch"> </p> <p id="finally"> </p> <script type="text/javascript"> function forFinally() { try { document.getElementById("try").innerHTML = " Try block is executed "; } catch (error) { document.getElementById("catch").innerHTML = " Catch block is executed additional Information: " + error; } finally { document.getElementById("finally").innerHTML = "Finally block is executed "; } } </script> </body> </html>

執行上述程式後,將顯示一個按鈕。

單擊它將顯示 try 和 catch 執行的結果。

示例 2

以下是 try、catch 和 finally 的另一個示例:

<!DOCTYPE html> <html> <body> <h2>Finally - JavaScript</h2> <p>Please input a number between 5 and 10:</p> <input id="demo" type="text"> <button type="button" onclick="tryFinally()">Test Input</button> <p id="try"></p> <p id="message"></p> <script> function tryFinally() { const message = document.getElementById("message"); message.innerHTML = ""; let x = document.getElementById("demo").value; try { if(x == "") document.getElementById("try").innerHTML = "Please provide the specific input as mentioned"; if(isNaN(x)) document.getElementById("try").innerHTML = "Its is Not a Number"; if(x > 10) document.getElementById("try").innerHTML = "Input is greater than 10"; if(x < 5) document.getElementById("try").innerHTML = "Given input is less than 5"; if(x>5 && x<10) document.getElementById("try").innerHTML = "Given input is as required"; } finally{ message.innerHTML = "This is the finally block executed after the try block" } } </script> </body> </html>

執行上述程式後,將顯示一個文字框和一個按鈕,要求輸入 5 到 10 之間的數字。

  • 如果輸入相同的數字(5 到 7 之間的數字),則會顯示一條成功訊息“輸入符合要求”。

  • 如果輸入的值大於 10,則訊息為“輸入大於 10”。

  • 同樣,如果輸入的值小於 5,則輸出訊息為“輸入小於 5”。

在所有情況下,finally 都會在 try 塊之後執行,顯示“這是 try 塊執行後執行的 finally 塊”。

更新時間: 2022年8月25日

954 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.