简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM