After writing code that can be boiled down to the following:
var size=-1;
var arr=new byte[size];
I was surprised that it threw an OverflowException. The docs for OverflowException state:
The exception that is thrown when an arithmetic, casting, or conversion operation in a checked context results in an overflow.
I couldn't see how providing a negative size for and array length fits into the description given for this exception, so delved a little deeper and found that this is indeed the specified behaviour:
The computed values for the dimension lengths are validated as follows. If one or more of the values are less than zero, a System.OverflowException is thrown and no further steps are executed.
I wonder why OverflowException was chosen. It's pretty misleading if you ask me. It cost me at least 5 minutes of investigation (not counting my musings here). Can anyone shed any light on this (to my thinking) peculiar design decision?
The NegativeArraySizeException is a runtime exception in Java that occurs when an application attempts to create an array with a negative size. Since the NegativeArraySizeException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor.
Array dimensions cannot have a negative size.
Negative Array Exception occurs when the input size of the array give is a negative number. This can be handled by a try-catch block.
No, you cannot use a negative integer as size, the size of an array represents the number of elements in it, –ve number of elements in an array makes no sense.
This is almost certainly an optimization. The .NET framework code is pretty religious about checking arguments to let the programmer fall in the pit of success. But that doesn't come for free. The cost is fairly minuscule, many class methods take lots more machine cycles than is spent on the checking.
But arrays are special. They are the very core data structure in the framework. Almost every collection class is built on top of them. Any overhead put in the Array class directly impacts the efficiency of a lot of code that sits on top of it. Avoiding the check is okay, it gets implicitly checked anyway when the internal code needs to cast the value to unsigned. And it is very rare that it trips. So checking it twice is not quite worth the better exception message.
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