Rob*_*Rob 7 .net c# asp.net exception-handling
如果我有一个可以在两个地方抛出ArgumentException的例程,比如...
if (Var1 == null)
{
throw new ArgumentException ("Var1 is null, this cannot be!");
}
if (Val2 == null)
{
throw new ArgumentException ("Var2 is null, this cannot be either!");
}
Run Code Online (Sandbox Code Playgroud)
在我的调用过程中确定抛出两个异常中的哪一个的最佳方法是什么?
要么
我是以错误的方式做这件事吗?
Joã*_*elo 12
对于此特定方案,您应该使用ArgumentNullException并正确填充其ParamName属性,以便您知道null的参数.
该类ArgumentException还支持相同的属性,但您应该使用可用的最具体的异常类型.
使用这些类型的异常时,在使用同时接受消息和参数名称的构造函数时也要小心.订单在每种异常类型之间切换:
throw new ArgumentException("message", "paramName");
throw new ArgumentNullException("paramName", "message");
Run Code Online (Sandbox Code Playgroud)