| | | .NET异常代码编写 | | 2001-10-17·
·Eric Gunnerson··YESKY
| 上一页 1 2 3 4 5 6 下一页 Try-Finally
Finally 这个结构用来指定一段代码,即使在异常发生的情况下,这段代码也能够保证运行。通常,finally语句用来负责在异常发生后的清理工作。我们把前面的例子修改如下:
try { FileStream f = new FileStream(filename, FileMode.Create); StreamWriter s = new StreamWriter(f);
s.WriteLine("{0} {1}", "test", 55); s.Close(); f.Close(); } catch (IOException e) { Console.WriteLine("Error opening file {0}", filename); Console.WriteLine(e); } finally { if (f != null) f.Close(); } | 在这段修改过的代码中,即使发生了异常,finally语句也将被执行。
Using和Lock语句
前面我们看到的是一个非常常用的模式,C#提供了一种特殊的支持以促使程序员们写出正确的代码。Using语句可以被用来创建类似try-finally的代码:
using (FileStream f = new FileStream(filename, FileMode.Create)) { StreamWriter s = new StreamWriter(f);
s.WriteLine("{0} {1}", "test", 55); s.Close(); f.Close(); } catch (IOException e) { Console.WriteLine("Error opening file {0}", filename); Console.WriteLine(e); } | 这段代码等同于前面的例子。
Lock语句提供了一个类似的对System.Threading.Monitor类的包装,以保证即使在异常发生的情况下锁(locks)也能被释放。
上一页 1 2 3 4 5 6 下一页 | | | 感谢
访问天极网,如果您觉得该文章涉及版权问题,请看这里!
|
|