无涯教程-C# - finally语句

44 阅读1分钟

C#最后,finally被用来执行重要的代码,无论是否处理异常都要执行这些代码。必须在前面加上Catch或Try语句。

处理异常时的C#Finally示例

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示例

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

参考链接

www.learnfk.com/csharp/c-sh…