有什么方法可以在 vs 2010 或第三方应用程序中针对所有可能的异常自动生成方法可以抛出的“捕获”?
例如,如果我使用“Directory.CreateDirectory”,它将自动创建:
try
{
Directory.CreateDirectory("blabla");
}
catch (PathTooLongException)
{}
catch (DirectoryNotFoundException)
{}
catch (IOException)
{}
catch (ArgumentNullException)
{}
catch (UnauthorizedAccessException)
{}
最佳答案
有一个工具可以在您的代码中发现未处理的异常:Exception Hunter by Red Gate software .
事实证明,他们停止了它:
With the release of .NET 4.0 and WPF, the number of exceptions that the CLR can throw was greatly increased, to the point of being overwhelming. The exclusions list can no longer cover all the unlikely exceptions that the CLR may throw. This means that, although Exception Hunter will provide accurate results, these results will include a long list of potential exceptions, most of which are nothing to worry about.
这应该表明“捕获方法可能抛出的所有异常”可能不是一个好主意。通常的模式是有一个全局包罗万象
try {
...
} catch (Exception ex) {
logAndShowErrorMessage(ex);
}
仅在用户界面 (WinForms) 的顶级级别,或处理专用方法中的错误(WPF:Application.DispatcherUnhandledException,WebForms:Application.Error)。
仅在您预期该异常发生并且您知道如何具体处理该异常以及如何继续的异常情况下,您才直接在代码中处理异常之后执行程序。
作为旁注:您想要的看起来与称为“已检查的异常”的 Java 功能非常相似:它强制您处理异常或声明您的方法将重新抛出它。以下问题解释了为什么 C# 的设计者故意选择不包含此功能:
关于c# - 在 visual studio 2010 中自动生成捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10291902/