gpt4 book ai didi

c# - 抛出哪个空异常?

转载 作者:太空狗 更新时间:2023-10-29 22:08:05 26 4
gpt4 key购买 nike

考虑以下类和方法:

public class MyDto
{
public MyDtoChild Child {get; set;}
}

public void ProcessDto(MyDto myDto)
{
if(myDto == null) throw new ArgumentNullException("myDto");
this.CheckSomething(myDto.Child.ChildProperty);
}

如果使用 MyDto 调用,并在其自己的设备上留下一个空的 Child,这将抛出一个 NullReferenceException,这将非常难以诊断在更复杂的方法中。

通常,如果 myDto 为 null,我会在方法的开头抛出一个 ArgumentNullException,但如果 myDto.Children,则抛出什么是合适的异常> 为空? ArgumentNullExceptionNullReferenceException?自定义异常?

最佳答案

如前面的答案所述,它不应​​该是 ArgumentNullException,因为参数 myDTO 不是 NULL。对我来说,抛出 ArgumentException 更有意义因为传递给方法的参数不符合要求(您希望 Children 不为空)。此外,您的情况符合 ArgumentException 的描述:

ArgumentException is thrown when a method is invoked and at least one of the passed arguments does not meet the parameter specification of the called method.

关于c# - 抛出哪个空异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24648019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com