带有 XML 文档的示例方法:
// summary and param tags are here when you're not looking.
/// <exception cref="ArgumentNullException>
/// <paramref name="text" /> is null.
/// </exception>
public void Write(string text)
{
if (text == null)
throw new ArgumentNullException("text", "Text must not be null.");
// sync stuff...
}
Write(null)
按预期抛出异常。这是一个异步方法:
public async Task WriteAsync(string text)
{
if (text == null)
throw new ArgumentNullException("text", "Text must not be null.");
// async stuff...
}
WriteAsync(null)
, 在等待之前不会抛出异常。我应该ArgumentNullException
在exception
标签中指定吗?我认为这会让消费者认为调用WriteAsync
可能会抛出一个ArgumentNullException
并写下这样的东西:
Task t;
try
{
t = foo.WriteAsync(text);
}
catch (ArgumentNullException)
{
// handling stuff.
}
在异步方法中记录异常的最佳实践是什么?