try-catch-finally用法

1216

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

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

 

try-catch 语句由一个 try 块后跟一个或多个 catch 子句构成,这些子句指定不同的异常处理程序。

 

static void Main() 
{
    int x;
    try 
    {
        // Don't initialize this variable here.
        x = 123;
    }
    catch
    {
    }
    // Error: Use of unassigned local variable 'x'.
    Console.Write(x);
}

 

finally 块用于清除try中分配的资源,控制总是传递给 finally 块,与 try 块的退出方式无关。

也就是说,即使你在try内的程序有异常,或者是try内使用return退出,程序仍然会执行finally内语句。

// try-finally
using System;
public class MainClass
{
    static void Main()
    {
        int i = 123;
        string s = "Some string";
        object o = s;

        try
        {
            // Invalid conversion; o contains a string not an int
            i = (int)o;
        }
        finally
        {
            Console.Write("i = {0}", i);
        }
    }
}

 

 

留下一个答复

Please enter your comment!
Please enter your name here