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

前端 未结 8 1323
离开以前
离开以前 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 10:15

    The problem with catching and re-throwing the same exception is that, although .NET does its best to keep the stack trace intact, it always ends up getting modified which can make tracking down where the exception actually came from more difficult (e.g. the exception line number will likely appear to be the line of the re-throw statement rather than the line where the exception was originally raised). There's a whole load more information about the difference between catch/rethrow, filtering, and not catching here.

    When there is duplicate logic like this, what you really need is an exception filter so you only catch the exception types you're interested in. VB.NET has this functionality, but unfortunately C# doesn't. A hypothetical syntax might look like:

    try
    {
        // Call to a WebService
    }
    catch (Exception ex) if (ex is SoapException || ex is HttpException || /* etc. */)
    {
        // Log Error and eat it
    }
    

    As you can't do this though, what I tend to do instead is use a lambda expression for the common code (you could use a delegate in C# 2.0), e.g.

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

提交回复
热议问题