问题描述
我习惯使用一般的catch语句,我以一般方式处理这些异常。这是不好的做法吗如果是这样,我如何知道哪些特定的例外可以被抛出,哪些是我抓到的?-
是的,除了几个非常具体的情况,这是不好的做法。一个常见的情况我可以想到捕获所有异常的地方不是一个糟糕的想法是当您在应用程序即将自动关闭之前记录消息或堆栈跟踪(或者也许,您正在记录和重新开始)
-
只捕获你知道的可以处理的例外。不多不少。如果你不知道一个异常可以抛出一个方法,你不会正确处理它,所以不要抓住它。方法和库负责记录您应该能够处理的异常。另外,不要捕获指示逻辑失败的异常,例如
NullReferenceException
和ArgumentException
。这些表示您的软件中的真正错误,您应该修复,而不是您应该在运行时处理的。
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 exceptions could be thrown and which ones do I catch?
Yes, except in a couple of very specific cases that's bad practice. The one common case I can think of where catching all exceptions isn't a lousy idea is when you're logging a message or a stack trace just before the app is about to tear itself down (or, maybe, you're logging and rethrowing).
Catch only the exceptions you know you can handle. No more, no less. If you don't know an exception can be thrown from a method, you aren't going to handle it properly anyway so don't catch it. Methods and libraries are responsible for documenting exceptions that you should be able to handle. Also, don't catch exceptions that indicate a logic failure, such as
NullReferenceException
andArgumentException
. These indicate a genuine bug in your software that you should fix, not something that you should handle at runtime.
这篇关于在C#中,我如何知道要捕获哪些异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!