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

前端 未结 8 1269
离开以前
离开以前 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 09:56

    Sometimes that is to only way to handle "catch every exception" scenarios, without actually catching every exception.

    I think sometimes, say, lowlevel framework / runtime code needs to make sure that no exception is ever escaping. Unfortunately, there is also no way the framework code can know which exceptions are raised by the code executed by the thread.

    In that case a possible catch block could look like this:

    try
    {
       // User code called here
    }
    catch (Exception ex)
    {
       if (ExceptionIsFatal(ex))
         throw;
    
       Log(ex);
    }
    

    There are three important points here, however:

    1. This isn't something for every situation. In code reviews we are very picky about places where this is actually neccessary and thus allowed.
    2. The ExceptionIsFatal() method assures that we don't eat exceptions which should never be swallowed (ExecutionEngineException, OutOfMemoryException, ThreadAbortException, etc.)
    3. What is swallowed is carefully logged (event-log, log4net, YMMV)

    Typically, I'm all for the practice of letting uncaught exceptions simply "crash" the application by terminating the CLR. However, especially in server applications, this is sometimes not sensible. If one thread encounters a problem which is deemed non-fatal, there is no reason in ripping the whole process down, killing off all other running requests (WCF, for example, handles some cases this way).

提交回复
热议问题