Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I bother throwing an exception from this method?

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.

like image 771
user158485 Avatar asked Nov 29 '22 20:11

user158485


1 Answers

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.

like image 63
Peter Oehlert Avatar answered Dec 01 '22 08:12

Peter Oehlert