Exceptions priority in InputStream.read(byte[], int, int)

Raffaello Giulietti raffaello.giulietti at gmail.com
Tue Jun 23 15:34:08 UTC 2020


Yes, argument checking happening first is a sensible choice.

But if one considers the target of the method to be an implicit first 
argument, then, in the example, the stream would be checked first, 
possibly throwing IOException. On the other hand, if one only considers 
the explicit arguments, then the example would possibly throw 
NullPointerException or IndexOutOfBoundsException.



The point is that, in general, the order shall either be explicitly 
*unspecified* (which has costs for the consumer code) or be explicitly 
*specified*, and then almost forever if it resides in a popular library 
like java.io (which has costs for the provider code).

Sometimes life is hard...




On 2020-06-23 16:54, Martin Buchholz wrote:
> When there is a choice of exceptions to be thrown, it's not usually
> specified which one wins.
> Usually there's a natural order of operations that cause e.g. argument
> checking to happen first.
> Sometimes a code change can cause a different exception to be thrown,
> and that occasionally causes compatibility trouble.
> 
> On Tue, Jun 23, 2020 at 7:43 AM Raffaello Giulietti
> <raffaello.giulietti at gmail.com> wrote:
>>
>> Hi,
>>
>> the InputStream.read(byte[], int, int) method [1] can throw
>> * IOException
>> * NullPointerException
>> * IndexOutOfBoundsException
>>
>> Is there a recommended priority for the conditions associated to the
>> exceptions to be checked? For example, if the arguments are invalid and
>> the stream is already closed, which exception shall be thrown?
>>
>>
>> Greetings
>> Raffaello
>>
>> ----
>>
>> [1]
>> https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/io/InputStream.html#read(byte%5B%5D,int,int)



More information about the core-libs-dev mailing list