C# 属性

C# 抽象

C# 字符串

C# 泛型

C# 杂项

C# 新特性

C# finally 始终运行

C# finally 块用于执行无论是否处理异常都要执行的重要代码。它必须在 catch 或 try 块之前。


当一个异常抛出时,它会改变程序的执行流程。因此不能保证一个语句结束后,它后面的语句一定会执行,在 C# 中这个问题可以用 finally 解决。

为了确保一个语句总是能执行(不管是否抛出异常),需要将该语句放到一个 finally 块中,finally 要么紧接在 try 块之后,要么紧接在 try 块之后的最后一个 catch 处理程序之后。

只要程序进入与一个 finally 块关联的 try 块,则 finally 块始终都会运行 -- 即使发生了一个异常。



如果异常被处理,C# finally 示例

例子 (Example)

using System;  
public class ExExample  
{  
    public static void Main(string[] args)  
    {  
        try  
        {  
            int a = 10;  
            int b = 0;  
            int x = a / b;  
        }  
        catch (Exception e) { Console.WriteLine(e); }  
        finally { Console.WriteLine("Finally block is executed"); }  
        Console.WriteLine("Rest of the code");  
    }  
}

输出:

System.DivideByZeroException: Attempted to divide by zero.
Finally block is executed
Rest of the code

C# finally 示例如果未处理异常

例子 (Example)

using System;  
public class ExExample  
{  
    public static void Main(string[] args)  
    {  
        try  
        {  
            int a = 10;  
            int b = 0;  
            int x = a / b;  
        }  
        catch (NullReferenceException e) { Console.WriteLine(e); }  
        finally { Console.WriteLine("Finally block is executed"); }  
        Console.WriteLine("Rest of the code");  
    }  
}

输出:

Unhandled Exception: System.DivideBy


  • 使用社交账号登录,本站支持
全部评论(0)