Is this a bad practice to catch a non-specific exception such as System.Exception? Why?

前端 未结 8 1320
离开以前
离开以前 2020-11-29 09:21

I am currently doing a code review and the following code made me jump. I see multiple issues with this code. Do you agree with me? If so, how do I explain to my colleague t

8条回答
  •  半阙折子戏
    2020-11-29 10:16

    I am currently doing a code review and the following code made me jump. I see multiple issues with this code. Do you agree with me?

    Not totally, see below.

    • Catch a generic exception (Exception ex)

    In general, catching a generic exception is actually ok as long as you rethrow it (with throw;) when you come to the conclusion that you can't handle it. The code does that, so no immediate problem here.

    • The use of "if (ex is something)" instead of having another catch block

    The net effect of the catch block is that only SoapException, HttpException, etc. are actually handled and all other exceptions are propagated up the call stack. I guess functionality-wise this is what the code is supposed to do, so there's no problem here either.

    However, from a aesthetics & readability POV I would prefer multiple catch blocks to the "if (ex is SoapException || ..)". Once you refactor the common handling code into a method, the multiple catch blocks are only slightly more typing and are easier to read for most developers. Also, the final throw is easily overlooked.

    • We eat SoapException, HttpException and WebException. But if the Web Service failed, there not much to do.

    Here possibly lurks the biggest problem of the code, but it's hard to give advice without knowing more about the nature of the application. If the web service call is doing something that you depend on later then it's probably wrong to just log & eat the exceptions. Typically, you let the exception propagate to the caller (usually after wrapping it into e.g. a XyzWebServiceDownException), maybe even after retrying the webservice call a few times (to be more robust when there are spurious network issues).

提交回复
热议问题