If I have a routine that can throw an ArgumentException in two places, something like...
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!");
}
What’s the best way of determining in my calling procedure which of the two exceptions was thrown?
Or
Am I doing this in the wrong fashion?
For this specific scenario you should be using ArgumentNullException
and correctly fill it's ParamName
property so that you know the argument that is null.
The class ArgumentException
also supports the same property but you should used the most specific exception type available.
When using these types of exceptions also be careful when using the constructor that accept both the message and the parameter name. The orders are switched between each exception type:
throw new ArgumentException("message", "paramName");
throw new ArgumentNullException("paramName", "message");
Pass the name of the variable (Val1, Val2 etc) in the second argument to the ArgumentException constructor. This becomes the ArgumentException.ParamName property.
Your calling function should not care which line caused the exception. In either case an ArgumentException
was thrown, and both should be dealt with the same way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With