Search code examples
javaimagetry-catchimageicon

Why Java ImageIcon isn't enter catch clause?


When I try to create ImageIcon, I am getting this error:

sun.awt.image.ImageFormatException: Unsupported color conversion request
at sun.awt.image.JPEGImageDecoder.readImage(Native Method)
at sun.awt.image.JPEGImageDecoder.produceImage(Unknown Source)
at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
at sun.awt.image.ImageFetcher.run(Unknown Source)

And if this error occur then I want to load another image so I used try-catch like that:

  public Component getListCellRendererComponent(
        JList<?> list, Object value, int index, 
        boolean isSelected, boolean cellHasFocus ) 
{
    // Display the text for this item
    setText(value.toString());

    // Pre-load the graphics images to save time
    String iconurl=ABC.getCiconUrl();
    if(iconurl.isEmpty())
    {
        iconurl="img\\backgroundpic.png";
    }
    try {
        image = new ImageIcon(iconurl);
    } catch (Exception e) {
        image = new ImageIcon("img\\backgroundpic.png");
    }
    // Set the correct image
    setIcon( image );
    return this;
}

But even the error occur, it is not jumping into catch state. Why ?


Solution

  • If you look at the stack trace you'll notice that none of your functions is listed in it. The thread throwing the exception is a different one else from the thread that runs your code; it is a thread responsible for asynchronously loading images for ImageIcons, hence you can't catch that exception