异常处理语句:try-catch-finally
catch 和 finally 一起使用的常见方式是:在 try 块中获取并使用资源,在 catch 块中处理异常情况,并在 finally 块中释放资源。
有关重新引发异常的更多信息和示例,请参见
示例
C# | |
---|---|
public class EHClass { void ReadFile(int index) { // To run this code, substitute a valid path from your local machine string path = @"c:\users\public\test.txt"; System.IO.StreamReader file = new System.IO.StreamReader(path); char[] buffer = new char[10]; try { file.ReadBlock(buffer, index, buffer.Length); } catch (System.IO.IOException e) { Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message); } finally { if (file != null) { file.Close(); } } // Do something with buffer... } } |
本在线速查手册由www.w▫3▫x▫u▫e.com提供,请勿盗用!