c# - 在 visual studio 2010 中自动生成捕获

标签 c# visual-studio-2010 try-catch code-snippets

有什么方法可以在 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/

相关文章:

c# - 在 ASP MVC 和 Entity Framework 中提交后页面会自行重新加载

java - Java 中的 try-catch 语法糖

c# - 通过参数更新列名

c# - 按属性(property)共享值(value)排序列表

c# - 无法在 Visual Studio 2010 c# 中使用 SoundPlayer 播放声音

c - Visual Studio 2013 : Access violation when attempt to change value of variable obtained from LockResource()

c# - 使用 C# 获取 Active Directory 中用户的父 OU

visual-studio-2010 - Visual Studio 2010 SP1 Beta 安装缓慢

C++ 获取在 catch(...) block 中捕获的异常的描述

python 尝试:except:finally