Which types of exception not to catch?
A lot of times, it is mentioned to only catch exceptions which I can handle (throw, wrap and/or log, or perform some other actions).
Which exceptions cannot be handled? Is this the same meaning as should not be caught? I know that exceptions which may represent an object reference being null should not be caught, because they are programming errors and not user-provoked. Is there any other example? Another one is ExecutionEngineException
.
Also, is the cou开发者_运维知识库rse of action in a catch block always just between rethrow, wrap/rethrow and log? Is there ever a case where some other action needs to be performed in a catch block?
Thanks
The usual advice applies, only catch what you can handle. There's a utility function named IsCriticalException inside the framework that's pretty commonly used by parts of the framework code to decide whether or not to swallow an exception. Might as well go by that. It considers the following critical:
- NullReferenceException
- StackOverflowException (uncatchable)
- OutOfMemoryException
- ThreadAbortException
- ExecutionEngineException (uncatchable in 4.0)
- IndexOutOfRangeException
- AccessViolationException
It is a good list.
I would use Eric Lippert's advice and not catch "Fatal" exceptions:
https://ericlippert.com/2008/09/10/vexing-exceptions
The course of action in a catch block may not always be rethrow, wrap/retrow and log. I've seen where a db exception, like a deadlock, causes an exception to be thrown and then the catch logic attempts to perform the database action again in hope that the locked resource is no longer locked.
精彩评论