I'm performing some parameter validation in a method and throwing an exception where necessary. Do I need to bother manually throwing exceptions of this type? As long as the caller is wrapped in a try..catch block a similar exception is thrown regardless of whether the manual checks are in place.
public static Int16 ToInt16(this byte[] value, int startIndex, bool isBigEndian) {
// are these exceptions necessary?
if (value == null) {
throw new ArgumentNullException("value");
}
if ((startIndex + 1) >= value.Length) {
throw new ArgumentOutOfRangeException("startIndex");
}
return (isBigEndian)
? (Int16)((value[startIndex] << 8) | value[startIndex + 1])
: (Int16)((value[startIndex + 1] << 8) | value[startIndex]);
}
This is an extension method used for converting 2 bytes in an array to an Int16 with a way to toggle Big Endian or Little Endian conversion.
The value of throwing exceptions here is that rather than getting a null deref exception you're going to get an argument exception that most importantly tells you the argument that is invalid. The exception is also more explicitly pointing to the cause than a generic null deref which could be anything.
Given that this is an extension method which is already one level of indirection I think it's probably more useful to be complete and include the exceptions. Especially given that you've obviously already written it, but even as a matter of policy. If it weren't an extension method I could go either way. I might also use an assert instead depending on how buried the code was.
I don't know about presently but in the .Net 1.1 and 1.0 Frameworks, the JIT compiler would never inline a call that had a throw in it. To avoid this would often mean creating a different method which would throw the exception itself.
By the way you have an off by one error with startIndex + 1 > value.Length; it should be >= instead.
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