C#教程
C#控制语句
C#函数
C#数组
C#面向对象
C#命名空间和异常
C#文件IO
C#集合
C#多线程
C#其它

C# finally

C# finally

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
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4