由於異常結束了當前正在運行的方法,並且該方法可能打開了一個文件或網絡,需要在當前方法結束時關閉,因此可能會導致錯誤。為了克服這樣的問題,我們在C#中有一個特殊的保留關鍵字,叫做Finally,當try和catch區塊的執行停止時,就會執行這個Finally程式碼區塊,無論什麼情況導致執行停止,它都不會停止。不管try塊的執行是正常停止還是異常停止。 Finally程式碼區塊的主要目的是執行並釋放所佔用的資源,它寫在try和catch程式碼區塊之後.
文法:
try { //Block of code } // this can be optional catch { //Block of code } finally { //Block of code }
下面是C#的例子最後:
C# 程序,示範在程式中使用 Final 程式碼區塊。
代碼:
using System; //a class called program is defined class program { // a method called ClassA() is defined static void ClassA() { try { Console.WriteLine("We are inside class A"); //An exception is thrown throw new Exception("An exception is thrown"); } //finally block is executed regardless of the exception is handled or not finally { Console.WriteLine("This is the finally block of Class A"); } } // a method called ClassB() is defined static void ClassB() { try { Console.WriteLine("We are Inside class B"); return; } //finally block is executed regardless of the exception is handled or not finally { Console.WriteLine("This is the finally block of class B"); } } // Main Method is called public static void Main(String[] args) { try { ClassA(); } catch (Exception) { Console.WriteLine("The exception that is thrown is caught"); } ClassB(); } }
輸出:
說明:上面的程式中,程式就是定義的類別。然後定義了一個名為 ClassA 的方法,其中編寫了 try 和 finally 程式碼區塊。 try 區塊拋出一個稍後被捕獲的異常。然後無論異常是否被處理,都會執行Finally區塊。然後定義了一個名為ClassB的方法。然後無論異常是否被處理,都會執行finally區塊。然後呼叫main方法。
C# 程序,示範在具有異常處理的程序中使用finally關鍵字。
代碼:
using System; //a class called program is defined public class program { // Main Method is called static public void Main() { // two integer variables are defined to store two integers intnum = 10; int div = 0; //try and catch block is defined in which an exception is raised by try block and is handled by catch block try { int op = num / div; } catch (DivideByZeroException) { Console.WriteLine("The divisor can not be zero because it is impossible to divide by 0"); } // finally block is executed regardless of the exception is handled or not finally { Console.WriteLine("We are in the finally block"); } } }
輸出:
說明:在上面的程式中,定義了一個名為program的類別。然後呼叫 main 方法。然後定義兩個整數變數來儲存兩個整數。然後定義try和catch區塊,其中異常由try區塊引發並由catch區塊處理。然後無論異常是否被處理,都會執行finally區塊。
C# 程序,示範在沒有異常處理的程序中使用finally關鍵字。
代碼:
using System; //a class called program is defined public class program { // Main Method is called static public void Main() { // two integer variables are defined to store two integers intnum = 10; int div = 0; //try and catch block is defined in which an exception is raised by try block and is handled by catch block try { int op = num / div; } // finally block is executed regardless of the exception is handled or not finally { Console.WriteLine("We are in the finally block"); } } }
輸出:
說明:在上面的程式中,定義了一個名為program的類別。然後呼叫 main 方法。然後定義兩個整數變數來儲存兩個整數。然後定義try塊。然後無論異常是否被處理,都會執行finally區塊。程式的輸出如上面的快照所示。
結論:在本教程中,我們透過定義、語法、程式設計範例及其輸出來了解 C# 中的 finally 關鍵字的概念。
這是 C# 最終指南。在這裡,我們最後討論 C# 的簡介及其優點以及範例和程式碼實作。您也可以瀏覽我們其他推薦的文章以了解更多資訊 –
以上是C#終於的詳細內容。更多資訊請關注PHP中文網其他相關文章!