Don’t catch all exceptions

One of the best practices on exception is don’t catch all exceptions. There are many reasons why this is a best practice. For example, You want to look at the application state when the exception is thrown so that you can understand exactly why the exception is thrown. The exact state is often lost when exception is caught and application is continued.

Here is another example why should not catch all the exceptions.

One team found a strange deadlock when turning on fusion binding log. After a long try and diagnose, we finally understand what is going on.

By default fusion uses IE cache to store the binding log. To do so fusion uses wininet APIs.

In this particular case, wininet hits an access violation while holding a wininet lock. the access violation exception is propogated, caught, ignored, and continued. But the wininet lock is still held.

Later on when fusion calls wininet to store a log to IE cache, wininet waits on the lock indefinitely.

Comments (3)

  1. Mihailik says:

    Well, the problem in that particular case is wrong lock handling. Not using try/finally with locks (critical sections) is a serious bug.

    One could catch just very specific exception thrown in that case, and still have the same problem.

    It is exactly why C# introduced ‘lock’ statement, to force (implicit) try/finally usage.

  2. No, the right action here is to crash.

    You have no idea when an AV happens, what kind of important data it has corrupt. You can attempt to recover. But the recovery process may cause more damage, and eventually you can’t tell why the original AV happens.

    When something really bad happened, you want to preserve the state as much as possible so that you can tell exactly what was happening after the crash.

  3. Oleg Mihailik says:

    OK, you are right. In case of unknown exception the right action is to crash.

    But it still doesn’t mean one can use locks without try/finally.

    Well, may be C/C++ has many means of returning error, and sometimes we are awaiting for just HRESULT-like errors only. Therefore, for consistency it may be better not to handle exceptions. If that was the case, I agree with the strategy.