Question

I have java class with a method which gets an image from a website:

private Image image;
private int height;
private int width;
private String imageUri;

public Image getImage() {
    if (image == null) {
        log.info("Fetching image: " + imageUri);
        try {
            URL iURL = new URL(imageUri);
            ImageIcon ii = new ImageIcon(iURL);
            image = ii.getImage();
            height = image.getHeight(null);
            width = image.getWidth(null);
        } catch (SecurityException e) {
            log.error("Unable to fetch image: " + imageUri,e);
        } catch (MalformedURLException e) {
            log.error("Unable to fetch image: " + imageUri,e);
        }
    }
    return image;
}

The problem is that sometimes the imageUri I try to fetch gets redirected, causing the ImageIcon constructor to throw a java.lang.SecurityException - which is not caught by the catch clause, causing my program to terminate.

Can anyone suggest how I might catch this exception?

Thanks

Was it helpful?

Solution 4

Due to ImageIcon being extremely old school, and spawning a new thread (which i do not want) , my solution is as follows:

public Image getImage() {
    if (image == null) {
        log.info("Fetching image: " + imageUri);
        try { 
            URL iURL = new URL(imageUri);
            InputStream is = new BufferedInputStream(iURL.openStream());
            image = ImageIO.read(is);
            height = image.getHeight();
            width = image.getWidth();
        } catch (MalformedURLException e) {
            log.error("Unable to fetch image: " + imageUri, e);
        } catch (IOException e) {
            log.error("Unable to fetch image: " + imageUri, e);
        }
    }
    return image;
}

Any issues with redirects, dead links etc are now handled gracefully.

OTHER TIPS

The exception is being thrown by the constructor, which is not wrapped in the try block.

new ImageIcon(new URL(imageUri))

Using ImageIcon to load an image is sooooo 1998. You want ImageIO.read().

If the exception indeed thrown from getImage(), your code should catch it. SecurityException is Exception. You've got it wrong somewhere. For instance, place ImageIcon constructor under try. If it doesn't help, try

catch( Throwable th )

It's a bad habit though. Try at least to re-throw it (or a wrapper exception) after logging it.

This is an old thread - but I thought of adding an alternative answer since I got it after reaching the same problem and hitting this post.

Since I don't want to add more dependencies to my app (=javax) I used the solution suggested here to get the bitmap and then I used setImageBitmap in this case the SecurityException is caught

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top