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

后端 未结 20 2213
执笔经年
执笔经年 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 02:05

    The try..finally block will still throw any exceptions that are raised. All finally does is ensure that the cleanup code is run before the exception is thrown.

    The try..catch with an empty catch will completely consume any exception and hide the fact that it happened. The reader will be closed, but there's no telling if the correct thing happened. What if your intent was to write i to the file? In this case, you won't make it to that part of the code and myfile.txt will be empty. Do all of the downstream methods handle this properly? When you see the empty file, will you be able to correctly guess that it's empty because an exception was thrown? Better to throw the exception and let it be known that you're doing something wrong.

    Another reason is the try..catch done like this is completely incorrect. What you are saying by doing this is, "No matter what happens, I can handle it." What about StackOverflowException, can you clean up after that? What about OutOfMemoryException? In general, you should only handle exceptions that you expect and know how to handle.

    0 讨论(0)
  • 2020-11-28 02:05

    try {…} catch{} is not always bad. It's not a common pattern, but I do tend to use it when I need to shutdown resources no matter what, like closing a (possibly) open sockets at the end of a thread.

    0 讨论(0)
提交回复
热议问题