"finally"使用注意

先请大家看下面一段代码:
None.gif public   static   void  Test( string  fileName)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
string fileName;
InBlock.gif            System.IO.StreamReader sr
=null;
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                sr
=new System.IO.StreamReader(fileName);                
ExpandedSubBlockEnd.gif            }

InBlock.gif            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                sr.Close();
ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }

None.gif

以前我一直采用上面的方法关闭StreamReader, 我从没想到这样的写法在运行时会引起问题。今天我就遇到了莫明其妙的“未将对象引用设置到对象的实例”异常。因为这个异常很难跟踪,一开始我总是怀疑sr=new System.IO.StreamReader(fileName);后面的代码引起的异常,可是我将那部分代码全部注释, 还是有这个异常。后来,我注释掉sr.Close();才发现引起异常的真正原因。
原来在sr=new System.IO.StreamReader(fileName); 中,由于fileName路径不对,找不到相应的文件,抛出了异常,此时sr应该是null值,而在finally中执行sr.Close()就会引起“未将对象引用设置到对象的实例”异常。
正确的代码应该是这样:
None.gif public   static   void  Test( string  fileName)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
string fileName;
InBlock.gif            System.IO.StreamReader sr
=null;
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                sr
=new System.IO.StreamReader(fileName);                
ExpandedSubBlockEnd.gif            }

InBlock.gif            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if(sr!=null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    sr.Close();
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值