c # /. net에서 예외를 문서화하는 방법
현재 회사 내의 다른 개발자가 내부적으로 사용할 작은 프레임 워크를 작성 중입니다.
좋은 Intellisense 정보를 제공하고 싶지만 발생 된 예외를 문서화 하는 방법 을 잘 모르겠습니다 .
다음 예에서
public void MyMethod1()
{
MyMethod2();
// also may throw InvalidOperationException
}
public void MyMethod2()
{
System.IO.File.Open(somepath...); // this may throw FileNotFoundException
// also may throw DivideByZeroException
}
예외 문서화에 대한 마크 업은 다음과 같습니다.
/// <exception cref="SomeException">when things go wrong.</exception>
내가 이해하지 못하는 것은에 의해 호출 된 코드에 의해 발생하는 예외를 문서화하는 방법입니다 MyMethod1()
.
- 예외를 문서화해야합니까?
MyMethod2()
- 발생한 예외를 문서화해야합니까
File.Open()
?
가능한 예외를 문서화하는 가장 좋은 방법은 무엇입니까?
호출 할 수있는 메소드의 예외를 포함하여 코드에서 발생할 수있는 모든 예외를 문서화해야합니다.
목록이 약간 커지면 자체 예외 유형을 만들 수 있습니다. 메소드 내에서 발생할 수있는 모든 것을 잡아서 예외로 감싸서 던지십시오.
이 방법으로 수행 할 수있는 또 다른 장소는 메소드가 API에있는 경우입니다. 파사드가 여러 인터페이스를 단일 인터페이스로 단순화하는 것처럼 API는 여러 예외를 단일 예외로 단순화해야합니다. 발신자가 쉽게 코드를 사용할 수 있습니다.
Andrew의 우려에 대한 답변 (댓글)에는 세 가지 유형의 예외가 있습니다. 알지 못하는 것, 알거나 할 수없는 것, 알거나 할 수있는 것에는 예외가 있습니다.
당신이 모르는 사람들은 떠나고 싶어합니다. 빠른 실패의 원칙은 데이터가 손상 될 수있는 상태에 들어가는 것보다 앱이 중단되는 것보다 낫습니다. 충돌은 발생한 상황과 이유를 알려주며 "알지 못하는 것"목록에서 해당 예외를 제거하는 데 도움이 될 수 있습니다.
당신이 알고 있고 할 수없는 것은 OutOfMemoryExceptions와 같은 예외입니다. 극단적 인 경우에는 이와 같은 예외를 처리하고 싶을 수도 있지만, 꽤 놀라운 요구 사항이 없다면 첫 번째 범주와 같이 처리해야합니다. 당신이 할 이 이러한 예외를 문서화? 객체를 새로 만드는 모든 단일 메소드에서 OOM을 문서화하는 것은 어리석은 것처럼 보일 것입니다.
당신이 알고 있고 할 수있는 것은 문서화하고 포장해야하는 것들입니다.
여기에서 예외 처리에 대한 몇 가지 지침을 찾을 수 있습니다 .
표준 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.");
}
}
이 방법으로 수행 할 수있는 값은 발생할 수있는 알려진 예외에 대한 문서를 제공한다는 것입니다. 이 문서는 Visual Studio를 사용하는 경우 인텔리전스로 제공되며 나중에 예상 할 수있는 예외를 상기시킬 수 있습니다.
한 가지 유형의 예외를 처리 할 수있는 반면 다른 유형은 심각한 문제로 인해 수정할 수 없으므로 특정 예외 유형을 지정하려고합니다.
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 Plugin for ReSharper, which adds an option to generate XML comments for thrown exceptions.
Update: It seems that Agen Johnson is not available for R# 8, checkout Exceptional for ReSharper as an alternative...
Step 1: GhostDoc generates the XML comment (Ctrl-Shift-D), while Agent Johnson plugin for ReSharper suggests documenting the exception as well:
Step 2: Use ReSharper's shortcut key (Alt-Enter) to add the exception documentation as well:
step 2 http://i41.tinypic.com/osdhm
Hope that helps :)
From what I understand, the intention of using the <exception> element is to use it when decorating methods, not exceptions:
/// <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 explicitly thrown by your own code should be documented.
As far as getting any more specific than that, perhaps you can catch and throw your own customized exceptions?
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
might be thrown, etc.
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.
You could consider retrowing them, if you cannot handle or solve the exception. Mostly packaged/wrapped in a more meaningfull exception for the caller.
Indeed, as it has been already answered, the way to document the exceptions is using XML Comments.
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.
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.
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.
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.
참고URL : https://stackoverflow.com/questions/461306/how-to-document-thrown-exceptions-in-c-net
'programing tip' 카테고리의 다른 글
현재 Git에서 체크 아웃 된 커밋 찾기 (0) | 2020.06.24 |
---|---|
Go로 시작하는 기능이 없습니까? (0) | 2020.06.24 |
여기서 XPath contains ()를 사용하는 방법은 무엇입니까? (0) | 2020.06.24 |
다른 포트로 아파치 리디렉션 (0) | 2020.06.24 |
bash 스크립트에서 다른 명령으로 매개 변수를 어떻게 전달합니까? (0) | 2020.06.24 |