由于异常结束了当前正在运行的方法,并且该方法可能打开了一个文件或网络,需要在当前方法结束时关闭,因此可能会导致错误。为了克服这样的问题,我们在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中文网其他相关文章!