编写异常助手方法

时间:2019-04-03 03:03:24

标签: c# exception syntax throw propagation

我是C#的新手,正在练习引发Exception。从助手方法中抛出异常以缩短所需代码量是否是一种好习惯?像这样:

    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抛出异常”的文档吗?任何信息都会有所帮助!谢谢

1 个答案:

答案 0 :(得分:4)

我认为您应该改用以下模式:

.getChildren()

为什么?

  • 您公开了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; } } 作为扩展方法,说实话这很奇怪
  • 如果您查看https://referencesource.microsoft.com/#q=throwif,就会发现它们从未公开
  • 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); } }

enter image description here

只需查看不使用该辅助方法的区别即可:

enter image description here

很清楚错误是从哪里来的。

您可能需要此方法:

  • 如果您实际上在数百个地方使用它
  • 如果要将消息翻译成用户的文化(例如中文)