9

在 C# 中使用 XML 注释,我可以记录一个方法可能会引发异常:

<exception cref="FooException">Thrown if foo is invalid.</exception>

但是,如果一个方法在其 XML 文档中没有exception标签,这可能意味着以下两种情况之一:

  1. 作者彻底测试了该方法,确保它永远不会抛出异常,并希望通过不添加exception标签来记录这一事实。
  2. 作者并不关心记录异常,所以这个方法可能会抛出任何东西。

根据我的经验,通常是第二种情况。那么问题来了:

如何明确记录方法永远不会引发异常?

到目前为止,我想出的最好的方法就是在方法中简单地提及它summary,例如“此方法不会引发异常”。但我想知道是否有更正式的方式来表达这一点,比如throw()在 C++ 中(尽管这可能是一个不好的例子)。

4

1 回答 1

2

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. You generally can't guarantee that a system exception won't be thrown. We may however guarantee that no ApplicationException is ever thrown.

1. With contracts

With code contracts, you may use EnsuresOnThrow post-conditions:

    Contract.EnsuresOnThrow<ApplicationException>( false );

2. Without contracts

Wrap the body of your code in a global try/catch, and assert False in the catch block.

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.

于 2014-04-07T09:18:09.933 回答