저는 C#을 처음 접했고 예외를 던지는 연습을하고있었습니다. 필요한 코드의 양을 줄이기 위해 도우미 메서드에서 예외를 throw하는 것이 좋은 방법입니까? 이렇게 :
public static void ThrowExcIfNull<T>(this T[] array)
{
if (array == null) throw new ArgumentNullException("Array is null");
}
/// <summary>
/// Does Something
/// </summary>
/// <param name="x">The int array to be used</param>
/// <exception cref="ArgumentNullException">Thrown when the string is
/// null</exception> //Is this correct?
/// <returns>Some integer</returns>
public static int SomeMethod(this int[] x)
{
ThrowExcIfNull(x);
//Some code here
}
또한 "someMethod에서 예외가 발생하고 있습니다"라는 Document를 작성해도됩니까? 모든 정보가 도움이 될 것입니다! 감사
대신 다음 패턴을 사용해야한다고 생각합니다.
using System;
public static class MyExtensions
{
/// <summary>
/// Magic method.
/// </summary>
/// <param name="source">
/// The source array.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="source" /> is <c>null</c>.
/// </exception>
/// <returns>
/// Some magic value only you know about.
/// </returns>
public static int SomeMethod(this int[] source)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return 42;
}
}
왜?
ThrowExcIfNull
을 노출했습니다. 솔직히 말해서 이상합니다.CancellationToken.ThrowIfCancellationRequested
를 제외하고 예외적 인 상황입니다.이러한 방법을 절대적으로 원하는 경우
디버그하기 쉽도록 매개 변수 이름을 전달하십시오.
using System;
public static class MyExtensions
{
public static int SomeMethod(this int[] source)
{
ThrowIfNull(source, nameof(source));
return 42;
}
private static void ThrowIfNull(object value, string parameter)
{
if (value == null)
throw new ArgumentNullException(parameter);
}
}
하지만 이제 또 다른 문제가 있습니다. 스택 추적에 표시되는 첫 번째 메서드는 ThrowExcIfNull
입니다.
해당 도우미 메서드를 사용하지 않고 차이점을 살펴보십시오.
오류의 원인이 명확합니다.
다음 메소드가 필요할 것입니다.
출처 : https://stackoverflow.com/questions/55486407/writing-an-exception-helper-method