C#异常处理中try和catch语句及finally语句的用法示例
使用 try/catch 处理异常 class TestTryCatch { static int GetInt(int[] array,int index) { try { return array[index]; } catch (System.IndexOutOfRangeException e) // CS0168 { System.Console.WriteLine(e.Message); // Set IndexOutOfRangeException to the new exception's InnerException. throw new System.ArgumentOutOfRangeException("index parameter is out of range.",e); } } }
static void CodeWithoutCleanup() { System.IO.FileStream file = null; System.IO.FileInfo fileInfo = new System.IO.FileInfo("C:file.txt"); file = fileInfo.OpenWrite(); file.WriteByte(0xF); file.Close(); } 为了将上面的代码转换为 try-catch-finally 语句,需要将清理代码与工作代码分开,如下所示。 static void CodeWithCleanup() { System.IO.FileStream file = null; System.IO.FileInfo fileInfo = null; try { fileInfo = new System.IO.FileInfo("C:file.txt"); file = fileInfo.OpenWrite(); file.WriteByte(0xF); } catch(System.UnauthorizedAccessException e) { System.Console.WriteLine(e.Message); } finally { if (file != null) { file.Close(); } } } 因为在 OpenWrite() 调用前,try 块内随时都有可能发生异常,OpenWrite() 调用本身也有可能失败,所以我们无法保证该文件在我们尝试关闭它时处于打开状态。 finally 块添加了一项检查,以确保在调用 Close 方法前,FileStream 对象不为 null。如果没有 null 检查,finally 块可能引发自身的 NullReferenceException,但是应当尽可能避免在 finally 块中引发异常。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |