C# --try catch finally

catchfinally 一起使用的常见方式是:在 try 块中获取并使用资源,在catch 块中处理异常情况,并在finally 块中释放资源。

finally 块用于清除 try 块中分配的任何资源,以及运行任何即使在发生异常时也必须执行的代码。控制总是传递给 finally 块,与 try 块的退出方式无关。

 

复制

// try_catch_finally.cs
using System;
public class EHClass
{
    static void Main()
    {
        try
        {
            Console.WriteLine("Executing the try statement.");
            throw new NullReferenceException();
        }
        catch (NullReferenceException e)
        {
            Console.WriteLine("{0} Caught exception #1.", e);
        }
        catch
        {
            Console.WriteLine("Caught exception #2.");
        }
        finally
        {
            Console.WriteLine("Executing finally block.");
        }
    }
}
示例输出
Executing the try statement.
System.NullReferenceException: Object reference not set to an instance of an object.
   at EHClass.Main() Caught exception #1.
Executing finally block.

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值