如何在 c#/.net 中记录抛出的异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/461306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to document thrown exceptions in c#/.net
提问by Arnold Zokas
I am currently writing a small framework that will be used internally by other developers within the company.
我目前正在编写一个小型框架,供公司内的其他开发人员在内部使用。
I want to provide good Intellisense information, but I am not sure howto document thrown exceptions.
我想提供良好的 Intellisense 信息,但我不确定如何记录抛出的异常。
In the following example:
在以下示例中:
public void MyMethod1()
{
MyMethod2();
// also may throw InvalidOperationException
}
public void MyMethod2()
{
System.IO.File.Open(somepath...); // this may throw FileNotFoundException
// also may throw DivideByZeroException
}
I know the markup for documenting exceptions is:
我知道记录异常的标记是:
/// <exception cref="SomeException">when things go wrong.</exception>
What I don't understand is how to document exceptions thrown by code called byMyMethod1()
?
我不明白的是如何记录由调用的代码引发的异常MyMethod1()
?
- Should I document exceptions thrown by
MyMethod2()
- Should I document exceptions thrown by
File.Open()
?
- 我应该记录抛出的异常吗
MyMethod2()
- 我应该记录抛出的异常
File.Open()
吗?
What would be the best way to document possible exceptions?
记录可能的异常的最佳方式是什么?
采纳答案by chills42
You should document every exception that might be thrown by your code, including those in any methods that you might call.
您应该记录您的代码可能抛出的每个异常,包括您可能调用的任何方法中的异常。
If the list gets a bit big, you might want to create your own exception type. Catch all the ones you might encounter within your method, wrap them in your exception, and throw that.
如果列表有点大,您可能需要创建自己的异常类型。捕获您在方法中可能遇到的所有异常,将它们包装在您的异常中,然后抛出该异常。
Another place you might want to do it this way is if your method is on the face of your API. Just like a facade simplifies multiple interfaces into a single interface, your API should simplify multiple exceptions into a single exception. Makes using your code easier for callers.
您可能希望以这种方式执行此操作的另一个地方是您的方法是否位于 API 的表面。就像 Facade 将多个接口简化为单个接口一样,您的 API 应该将多个异常简化为单个异常。使调用者更容易使用您的代码。
To answer some of Andrew's concerns (from the comments), there are three types of exceptions: Ones you don't know about, ones you know about and can't do anything about, and ones you know about and can do something about.
为了回答 Andrew 的一些担忧(来自评论),存在三种类型的例外:您不知道的例外、您了解但无法做任何事情的例外以及您了解且可以做些什么的例外。
The ones you don't know about you want to let go. Its the principal of failing fast--better your app to crash than enter a state where you might end up corrupting your data. The crash will tell you about what happened and why, which may help move that exception out of the "ones you don't know about" list.
那些你不知道的你想放手。它是快速失败的原则——让你的应用程序崩溃而不是进入可能最终破坏数据的状态。崩溃将告诉您发生了什么以及为什么发生,这可能有助于将该异常从“您不知道的”列表中删除。
The ones you know about and can't do anything about are exceptions like OutOfMemoryExceptions. In extreme cases you might want to handle exceptions like this, but unless you have some pretty remarkable requirements you treat them like the first category--let 'em go. Do you haveto document these exceptions? You'd look pretty foolish documenting OOMs on every single method that new-s up an object.
您知道但无能为力的是像 OutOfMemoryExceptions 这样的异常。在极端情况下,您可能希望像这样处理异常,但除非您有一些非常显着的要求,否则您将它们视为第一类——让他们去吧。您是否必须记录这些例外情况?为对象的每个新方法记录 OOM 看起来很愚蠢。
The ones you know about and can do something about are the ones you should be documenting and wrapping.
您知道并可以做些什么的是您应该记录和包装的那些。
You can find some more guidelines on exception handling here.
回答by GvS
You should document all exceptions that could possibly be thrown by your method.
您应该记录您的方法可能抛出的所有异常。
To hide the implementation details, I would try to handle some exceptions from MyMethod2 myself.
为了隐藏实现细节,我会尝试自己处理来自 MyMethod2 的一些异常。
You could consider retrowing them, if you cannot handle or solve the exception. Mostly packaged/wrapped in a more meaningfull exception for the caller.
如果您无法处理或解决异常,您可以考虑对它们进行追溯。主要打包/包装在对调用者更有意义的异常中。
回答by Damien
Document expected exceptions in your method, in your example I would let the user know that that method can throw a file not found exception.
在您的方法中记录预期的异常,在您的示例中,我会让用户知道该方法可以抛出文件未找到异常。
Remember that it is to inform the caller of what to expect so they can choose how to deal with it.
请记住,这是通知呼叫者期望的内容,以便他们可以选择如何处理。
回答by Daniel Schaffer
From what I understand, the intention of using the <exception> element is to use it when decorating methods, not exceptions:
据我了解,使用 <exception> 元素的目的是在装饰方法时使用它,而不是异常:
/// <summary>Does something!</summary>
/// <exception cref="DidNothingException">Thrown if nothing is actually done.</exception>
public void DoSomething()
{
// There be logic here
}
Exceptions that can be thrown by other methods that are called should be caught, handled and documented in those methods. Exceptions that could possibly thrown by .NET, or exceptions that are explicitlythrown by your own code should be documented.
应该在这些方法中捕获、处理和记录可以由被调用的其他方法抛出的异常。.NET 可能抛出的异常或您自己的代码显式抛出的异常应该记录在案。
As far as getting any more specific than that, perhaps you can catch and throw your own customized exceptions?
至于比这更具体的内容,也许您可以捕获并抛出您自己的自定义异常?
回答by chills42
You should use the standard xml documentation.
您应该使用标准的 xml 文档。
/// <exception cref="InvalidOperationException">Why it's thrown.</exception>
/// <exception cref="FileNotFoundException">Why it's thrown.</exception>
/// <exception cref="DivideByZeroException">Why it's thrown.</exception>
public void MyMethod1()
{
MyMethod2();
// ... other stuff here
}
/// <exception cref="FileNotFoundException">Why it's thrown.</exception>
/// <exception cref="DivideByZeroException">Why it's thrown.</exception>
public void MyMethod2()
{
System.IO.File.Open(somepath...);
}
/// <exception cref="FileNotFoundException">Why it's thrown.</exception>
public void MyMethod3()
{
try
{
MyMethod2();
}
catch (DivideByZeroException ex)
{
Trace.Warning("We tried to divide by zero, but we can continue.");
}
}
The value in doing it this way is that you are providing documentation of the known exceptions that can occur. This documentation is available in the intellisense if you are using visual studio and can remind you (or others) later of the exceptions that you can expect.
这样做的价值在于您提供了可能发生的已知异常的文档。如果您使用的是 Visual Studio,则可以在智能感知中找到此文档,并且可以稍后提醒您(或其他人)您可以预期的异常情况。
You want to specify the specific exception types, because you may be able to handle one type of exception, while other types are the result of a serious issue and can not be corrected.
您要指定特定的异常类型,因为您可能能够处理一种类型的异常,而其他类型则是严重问题的结果并且无法更正。
回答by Rowland Shaw
Part of the contract for your method should be to check that the pre-conditions are valid, so:
您的方法合同的一部分应该是检查先决条件是否有效,因此:
public void MyMethod2()
{
System.IO.File.Open(somepath...); // this may throw FileNotFoundException
}
becomes
变成
/// <exception cref="FileNotFoundException">Thrown when somepath isn't a real file.</exception>
public void MyMethod2()
{
FileInfo fi = new FileInfo( somepath );
if( !fi.Exists )
{
throw new FileNotFoundException("somepath doesn't exists")
}
// Maybe go on to check you have permissions to read from it.
System.IO.File.Open(somepath...); // this may still throw FileNotFoundException though
}
With this approach, it's easier to document all the exceptions you explicitly throw without having to also document that a OutOfMemoryException
mightbe thrown, etc.
使用这种方法,可以更轻松地记录您显式抛出的所有异常,而无需记录OutOfMemoryException
可能抛出的异常等。
回答by Igal Tabachnik
You can make your documentation process easier by using several great add-ins. One of them is GhostDoc, a free add-in for Visual Studio which generates XML-doc comments. Also, if you use ReSharper, have a look at the excellent Agent Johnson Pluginfor ReSharper, which adds an option to generate XML comments for thrown exceptions.
您可以通过使用多个出色的插件来简化文档处理过程。其中之一是GhostDoc,它是Visual Studio 的免费插件,可生成 XML 文档注释。此外,如果您使用ReSharper,请查看用于 ReSharper的优秀Agent Johnson 插件,它添加了一个选项来为抛出的异常生成 XML 注释。
Update:It seems that Agen Johnson is not available for R# 8, checkout Exceptional for ReSharperas an alternative...
更新:似乎 Agen Johnson 不适用于 R# 8,请查看 ReSharper 的 Exceptional作为替代...
Step 1: GhostDoc generates the XML comment (Ctrl-Shift-D), while Agent Johnson plugin for ReSharper suggests documenting the exception as well:
步骤 1:GhostDoc 生成 XML 注释 (Ctrl-Shift-D),而 ReSharper 的 Agent Johnson 插件也建议记录异常:
Step 2: Use ReSharper's shortcut key (Alt-Enter) to add the exception documentation as well:
步骤 2:使用 ReSharper 的快捷键 (Alt-Enter) 添加异常文档:
step 2 http://i41.tinypic.com/osdhm
第 2 步 http://i41.tinypic.com/osdhm
Hope that helps :)
希望有帮助:)
回答by Igal Tabachnik
Indeed, as it has been already answered, the way to document the exceptions is using XML Comments.
事实上,正如已经回答的那样,记录异常的方法是使用 XML 注释。
In addition to the plugins, you can also use static analysis tools that can be integrated with TFS to be sure you have the exceptions documented.
除了插件之外,您还可以使用可与 TFS 集成的静态分析工具,以确保记录异常。
In the links below you can see how to build a custom rule for StyleCop to validate the exceptions thrown by your methods are being documented.
在下面的链接中,您可以看到如何为 StyleCop 构建自定义规则以验证您的方法抛出的异常是否被记录。
http://www.josefcobonnin.com/post/2009/01/11/Xml-Documentation-Comments-Exceptions-I.aspxhttp://www.josefcobonnin.com/post/2009/01/15/Xml-Documentation-Comments-Exceptions-II.aspx
http://www.josefcobonnin.com/post/2009/01/11/Xml-Documentation-Comments-Exceptions-I.aspx http://www.josefcobonnin.com/post/2009/01/15/Xml-Documentation -Comments-Exceptions-II.aspx
Regards.
问候。