In C#, how do I know which exceptions to catch?

前端 未结 11 1364
抹茶落季
抹茶落季 2020-12-30 08:33

I\'ve gotten in the habit of using a general catch statement and I handle those exceptions in a general manner. Is this bad practice? If so, how do I know which specific exc

11条回答
  •  孤独总比滥情好
    2020-12-30 09:15

    Documentation will often describe what exceptions a method might throw and the conditions under which that might happen. This is especially the case with Microsoft's reference documentation for the .NET framework.

    In my view, exceptions should only be caught if you have a good reason to catch them. This usually means that catching and handling them in a generic manner is unnecessary. Logging exceptions (a very common activity in an exception handler) should only happen at the bottom of the call stack or whenever you don't rethrow the (possibly wrapped) exception , which should be rare. If you have some action you want to take place at every frame in the call stack when an exception is bubbling down, take a look at Aspect Oriented Programming (AOP) techniques.

提交回复
热议问题