C#错误与异常处理

C# 提供了几个关键字(try、catch 和 finally),程序可以用这些关键字检测异常、处理异常并继续运行。这些关键字是让应用程序更可靠的非常有用的工具。

class tryAndCatch
{
     public static int main()
    {
        int x=0,y=0;
        try
            {
                    x=12/y;
            }
            catch(System.DivideByZeroException)  
             {
                   //Error code here
              }
    }
}    

finally 块中包含的代码始终会执行,无论是否发生异常。使用 finally 块来确保资源已返回:例如,确保文件已关闭。

//例如,在我们进行读写问操作时,产生了IO错误,这时就需要在finally里面来将文件关闭,否则将会破坏文件。
try
{
    // Code to try here.
}
catch (SomeSpecificException ex)
{
    // Code to handle exception here.
}
finally
{
    // Code to execute after try (and possibly catch) here.
}

您也可以使用 throw 关键字来引发自己的异常

static void DoWork(int x)
    {
        if (x > 5)
        {
            throw new System.ArgumentOutOfRangeException("X is too large");
        }
    }

 

posted @ 2016-08-24 22:55  SWordStudio  阅读(309)  评论(0编辑  收藏  举报