if语句能检查错误但必须在运行时try/catch语句能在编译时检查异常 处理异常和错误>finally块的用途 当打开文件操作发生错误虽然捕捉到异常但资源没被释放所以finally块可用来释放资源或其它 代码 using System; using SystemCollectionsGeneric; using SystemText; using SystemIO; namespace FinallyDemo { class Program { static void Main(string[] args) { const string filePath = @C:\FinallyDemotxt; FileStream fs=null; try { ConsoleWriteLine(开始执行文件的比较操作); fs = new FileStream(filePath FileModeCreateNew FileAccessReadWrite); byte[] bytes = EncodingDefaultGetBytes(这是一个字符串将插入到文本文件); //向流中写入指定的字节数组 fsWrite(bytesbytesLength); //将缓沖区的内容存储到媒介并清除缓沖区 fsFlush(); //将流指针移到开头 fsSeek( SeekOriginBegin); byte[] bytes = new byte[bytesLength]; //从 fsRead(bytes bytesLength); string str = EncodingDefaultGetString(bytes); ConsoleWriteLine(从文件中读出的字符串为 + EnvironmentNewLine+str); } catch (IOException ex) { ConsoleWriteLine(发生了文件处理的错误! + exMessage); } finally { ConsoleWriteLine(不论是否发生异常都会执行finally到这里); if (fs != null) { fsClose(); } ConsoleReadLine(); } } } } |