Why is try {…} finally {…} good; try {…} catch{} bad?

后端 未结 20 2386
执笔经年
执笔经年 2020-11-28 01:30

I have seen people say that it is bad form to use catch with no arguments, especially if that catch doesn\'t do anything:

StreamReader reader=new  StreamRead         


        
20条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 01:48

    I agree with what seems to be the consensus here - an empty 'catch' is bad because it masks whatever exception might have occurred in the try block.

    Also, from a readability standpoint, when I see a 'try' block I assume there will be a corresponding 'catch' statement. If you are only using a 'try' in order to ensure resources are de-allocated in the 'finally' block, you might consider the 'using' statement instead:

    using (StreamReader reader = new StreamReader('myfile.txt'))
    {
        // do stuff here
    } // reader.dispose() is called automatically
    

    You can use the 'using' statement with any object that implements IDisposable. The object's dispose() method gets called automatically at the end of the block.

提交回复
热议问题