Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which of the two exceptions was called?

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?

like image 585
Rob Avatar asked May 17 '10 14:05

Rob


3 Answers

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");
like image 106
João Angelo Avatar answered Oct 11 '22 19:10

João Angelo


Pass the name of the variable (Val1, Val2 etc) in the second argument to the ArgumentException constructor. This becomes the ArgumentException.ParamName property.

like image 43
Polyfun Avatar answered Oct 11 '22 18:10

Polyfun


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.

like image 4
Justin Ethier Avatar answered Oct 11 '22 18:10

Justin Ethier