C# - finally语句

C# - finally语句 首页 / C#入门教程 / 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");
    }
}

输出:

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-finally.html

来源:LearnFk无涯教程网

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");
    }
}

输出:

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-finally.html

来源:LearnFk无涯教程网

Unhandled Exception: System.DivideBy

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

如何设计一个秒杀系统 -〔许令波〕

程序员的数学基础课 -〔黄申〕

Java并发编程实战 -〔王宝令〕

Go语言从入门到实战 -〔蔡超〕

网络排查案例课 -〔杨胜辉〕

说透低代码 -〔陈旭〕

手把手带你写一个MiniSpring -〔郭屹〕

结构执行力 -〔李忠秋〕

结构思考力 · 透过结构看问题解决 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)