Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rationale behind OverflowException thrown with negative array size?

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?

like image 815
spender Avatar asked Sep 21 '10 15:09

spender


People also ask

What happens if you pass negative size in array creation in Java?

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.

Can we declare array size as a negative number?

Array dimensions cannot have a negative size.

How do you resolve negative array size exception?

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.

Can we declare array size as a negative number in Java?

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.


1 Answers

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.

like image 112
Hans Passant Avatar answered Sep 29 '22 01:09

Hans Passant