mca*_*s20 11 c# exception-handling exception try-catch
我已经习惯使用一般的catch语句,并且我以一般方式处理这些异常.这是不好的做法吗?如果是这样,我如何知道可以抛出哪些特定异常以及我捕获哪些异常?
Gre*_*g D 19
是的,除了一些非常具体的情况,这是不好的做法.我可以想到捕获所有异常的一个常见情况并不是一个糟糕的想法,就是在应用程序即将崩溃之前记录消息或堆栈跟踪(或者,也许,您正在记录和重新抛出).
只捕获您知道可以处理的异常.不多也不少.如果您不知道可以从方法抛出异常,那么您无论如何都不会正确处理它,所以不要抓住它.方法和库负责记录您应该能够处理的异常.另外,不要捕获表示逻辑故障的异常,例如NullReferenceException
和ArgumentException
.这些表明您应该修复软件中的真正错误,而不是您应该在运行时处理的错误.
是的,这是不好的做法.经验法则:"抓住你能够回应的例外,让其他人去做."
try {
File.Open(usersChosenFile, FileMode.Open);
} catch(FileNotFoundException) {
// tell the user the file is gone, give them a chance to respond
// this is good
} catch(UnauthorizedAccessException) {
// this is good too
} catch(Exception) {
// what did you just catch? Who knows. What if its OutOfMemoryException?
// Do you really want to deal with that here? Let this one go by
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5145 次 |
最近记录: |