try-catch-finally(C# 参考)

来源:互联网 发布:排序算法应用 编辑:程序博客网 时间:2024/06/07 17:20

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

// try_catch_finally.csusing 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.

 

原创粉丝点击