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

后端 未结 20 2385
执笔经年
执笔经年 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:44

    Finally is executed no matter what. So, if your try block was successful it will execute, if your try block fails, it will then execute the catch block, and then the finally block.

    Also, it's better to try to use the following construct:

    using (StreamReader reader=new  StreamReader("myfile.txt"))
    {
    }
    

    As the using statement is automatically wrapped in a try / finally and the stream will be automatically closed. (You will need to put a try / catch around the using statement if you want to actually catch the exception).

提交回复
热议问题