Catching specific vs. generic exceptions in c#

后端 未结 7 1326
刺人心
刺人心 2020-12-08 06:16

This question comes from a code analysis run against an object I\'ve created. The analysis says that I should catch a more specific exception type than just the basic Except

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 06:32

    I agree that, in general, you should only catch exceptions you're expecting and understand how to handle. A few cases where I often don't do this:

    1. As mentioned above, if I'm capturing some sort of useful information to log and then rethrow.

    2. If I'm performing an asynchronous operation, such as handling queued messages or jobs in a worker thread, and I want to catch the exception for rethrowing in a different context. I also often use an ugly hack here that tricks the CLR into appending stack trace information, so that it's not lost when rethrowing in the new context.

    3. If I'm working with an isolated task or operation and I can handle the exception by shutting down the task, without shutting down the whole application. I often wish here that there were a top-level exception for truly fatal exceptions (like OutOfMemoryException), as I've been ignoring these. The proper way to handle this would be to run the isolated task in its own AppDomain, but I haven't had the available schedule time to implement this on a project yet.

提交回复
热议问题