[英]How to explicitly document that a method does not throw exceptions
Using XML comments in C#, I can document that a method may throw an exception: 在C#中使用XML注释,我可以记录一个方法可能抛出异常:
<exception cref="FooException">Thrown if foo is invalid.</exception>
However, if a method has no exception
tag in its XML documentation, this may mean one of two things: 但是,如果方法在其XML文档中没有exception
标记,则这可能意味着以下两种情况之一:
exception
tag. 作者彻底测试了该方法,确保它永远不会抛出异常,并希望通过不添加exception
标记来记录这一事实。 In my experience, the second is usually the case. 根据我的经验,第二种情况通常就是这样。 The question is, then: 那么问题是:
How do I explicitly document that a method will never throw an exception? 如何明确记录方法永远不会抛出异常?
The best I've come up with so far is to simply mention it in the method's summary
, like "This method does not throw exceptions". 到目前为止,我提出的最好的方法是在方法的summary
简单地提及它,例如“此方法不会抛出异常”。 But I was wondering if there is a more formal way to express this, like throw()
in C++ (even though that may be a bad example). 但我想知道是否有更正式的方式表达这一点,比如C ++中的throw()
(即使这可能是一个不好的例子)。
Adding it in the summary is good for documentation and communication with other developers. 在摘要中添加它有助于文档和与其他开发人员的通信。
You said you want to have a more formal way, tough. 你说你想要一个更正式的方式,艰难。 From what I know of C# (very little), Exception
has two main child classes, ApplicationException
and SystemException
. 根据我所知的C#(非常少), Exception
有两个主要的子类, ApplicationException
和SystemException
。 You generally can't guarantee that a system exception won't be thrown. 您通常无法保证不会抛出系统异常。 We may however guarantee that no ApplicationException
is ever thrown. 但是,我们可以保证不会抛出任何ApplicationException
。
With code contracts , you may use EnsuresOnThrow
post-conditions: 使用代码合同 ,您可以使用EnsuresOnThrow
后置条件:
Contract.EnsuresOnThrow<ApplicationException>( false );
Wrap the body of your code in a global try/catch
, and assert False
in the catch block. 在全局try/catch
包装代码体,并在catch块中断言False
。
In both cases , a static analyzer should understand that the assertion or post-condition can never be true when an exception occurs: thus, the application fullfills its contracts if and only if no exception is ever thrown from your function. 在这两种情况下 ,静态分析器应该理解,当发生异常时,断言或后置条件永远不会为真:因此,当且仅当您的函数没有抛出异常时,应用程序才会满足其合同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.