Hirak
Hirak

Reputation: 3649

when and how will ImageIO.write throw nullpointerexception?

In the

ImageIO.write(RenderedImage,String,File)

method, ImageOutputStream is created through

stream = createImageOutputStream(output);.

In the createImageOutputStream A runtime exception is caught and returns null from catch block.

try {
    iter = theRegistry.getServiceProviders(ImageOutputStreamSpi.class,true);
        } catch (IllegalArgumentException e) {
            return null;
        }

Can anyone help me understand:

  1. What is the reason behind catching a runtime exception here?(unless it is a crappy coding)
  2. On what condition, will the code throw illegal argument exception? (I dont see any reason for it to throw)

Please help.

Upvotes: 2

Views: 1042

Answers (1)

Harald K
Harald K

Reputation: 27094

It could be a case of code that has evolved over time and no one cared to clean up, or it could be that the implementers of ImageIO relied on the contract of ServiceRegistry, rather than the implementation details of it. In the current implementation of ImageIO and ServiceRegistry I don't see how this could ever happen.

The only good thing I can see about it, is that you could now potentially change the implementation of IIORegistry or ServiceRegistry to do lazy loading of categories for example, or perhaps flush out categories with no Service Providers (Spi) present. The contracts of the methods would not break, and the ImageIO class would still work as it does.

Now, back to the question in your question, the answer is it should never throw NullPointerException. *

If you really want to, you could get stream to be null, by de-registering the Spi for File (FileImageOutputStreamSpi). But even then, a well-behaved ImageWriter should throw an IllegalStateException indicating that the output has not been set, not a NullPointerException (of course, programming errors could cause NPEs in other places, but this is not normal flow).

Update:

*) As the OP himself pointed out in the linked answer, throwing of NullPointerException can indeed happen if you pass a File object pointing to a non-existing path. This happens because the FileImageOutputStreamSpi "swallows" the IOException caused by the RandomAccessFile constructor (it does print the stacktrace to standard out), and returns null. In my opinion, this breaks the contract in a more severe way than it would by just letting the IOException bubble up, or wrapping it in an IllegalArgumentException with the original exception as cause and some explanatory message. Consider filing a bug report, if it doesn't already exist one for this issue.

Upvotes: 1

Related Questions