c# - 来自 using block 的异常抛出

标签 c#

我有以下代码:

try{
    using (StreamReader reader = new StreamReader(...), Encoding.ASCII)){
        // Code that can throw an exception
    }
}catch (Exception error){
    // Display error...
}

如果 using block 中抛出异常,StreamReader 会发生什么?

我应该在关闭流的地方添加一个 finally 子句吗?

最佳答案

StreamReader 将由 using 自动处理,因为它本质上是一个嵌套的 try/finally:

try{
    StreamReader reader =  new StreamReader(...), Encoding.ASCII);
    try {
        // Code that can throw an exception     
    } finally {
        reader.Dispose();
    }
} catch (Exception error) {
    // Display error...
}

关于c# - 来自 using block 的异常抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9709884/

相关文章:

c# - web.config 和 app.config 更改的影响

c# - .NET 的缩略图库

c# - 为什么 appSettings 文件属性不允许父目录的路径?

c# - 'circular linked list builder' 的最快算法

c# - 从方法调用两个 Web 服务而不相互阻塞的最佳方法

c# - 选择列表中的项目时如何将属性值设置为 null

c# - 是否可以创建可以在 Windows 中以编程方式登录用户的服务或应用程序

c# - 字典 Keys.Contains 与 ContainsKey : are they functionally equivalent?

c# - 如何从另一个日期时间中减去一个日期时间并返回经过的小时数的两倍

c# - 类型删除 : Java vs C#