个性化阅读
专注于IT技术分析

C# finally块

点击下载

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

C#最终示例,如果处理了异常

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#最终示例

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)
未经允许不得转载:srcmini » C# finally块

评论 抢沙发

评论前必须登录!