编写异常辅助方法

问题描述 投票:1回答:1

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

    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抛出异常”是否可以?任何信息都会有帮助!谢谢

c# exception syntax throw propagation
1个回答
4
投票

我认为你应该使用以下模式:

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暴露为扩展方法,说实话这很奇怪
  • 如果你看看https://referencesource.microsoft.com/#q=throwif,你会发现他们从未公开过
  • 除了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

enter image description here

只需在不使用该辅助方法的情况下查看差异:

enter image description here

错误来自何处。

你可能会想要这个方法:

  • 如果你在数百个地方使用它
  • 如果要将消息翻译成用户的文化,例如中文
  • 等等
© www.soinside.com 2019 - 2024. All rights reserved.