Removing excessive try-catch blocks

前端 未结 8 2383
Happy的楠姐
Happy的楠姐 2021-02-14 19:10

I\'m refactoring a medium-sized WinForms application written by other developers and almost every method of every class is surrounded by a try-catch block. 99% of t

8条回答
  •  不知归路
    2021-02-14 19:21

    "To log exceptions appropriately and prevent them from propagating to the user, have an Application.ThreadException handler"

    Would you then be able to tell the user what happened? Would all exceptions end up there?

    "For cases where there's a resource that needs cleanup, leave the try-catch block as it is"

    You can use try-finally blocks as well if you wish to let the exception be handled elsewhere. Also consider using the using keyword on IDisposable resources.

    "In methods that "return-false-on-error", let the exception propagate and catch it in the caller instead"

    It depends on the method. Exceptions should occur only in exceptional situations. A FileNotFoundException is just weird for the FileExists() method to throw, but perfectly legal to be thrown by OpenFile().

提交回复
热议问题