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

前端 未结 8 1338
离开以前
离开以前 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:07

    The mantra is:

    • You should only catch exceptions if you can properly handle them

    Thus:

    • You should not catch general exceptions.

    In your case, yes, you should just catch those exceptions and do something helpful (probably not just eat them--you could throw after you log them).

    Your coder is using throw (not throw ex) which is good.

    This is how you can catch multiple, specific exceptions:

    try
    {
        // Call to a WebService
    }
    catch (SoapException ex)
    {
        // Log Error and eat it
    }
    catch (HttpException ex)
    {
        // Log Error and eat it
    }
    catch (WebException ex)
    {
        // Log Error and eat it
    }
    

    This is pretty much equivalent to what your code does. Your dev probably did it that way to avoid duplicating the "log error and eat it" blocks.

提交回复
热议问题