我是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抛出异常”的文档吗?任何信息都会有所帮助!谢谢
答案 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;
}
}
作为扩展方法,说实话这很奇怪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);
}
}
:
只需查看不使用该辅助方法的区别即可:
很清楚错误是从哪里来的。
您可能需要此方法: