1

我有一个带有从网站获取图像的方法的 java 类:

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;
}

问题是有时我尝试获取的 imageUri 被重定向,导致 ImageIcon 构造函数抛出 java.lang.SecurityException - catch 子句没有捕获,导致我的程序终止。

谁能建议我如何捕捉这个异常?

谢谢

4

5 回答 5

1

构造函数抛出异常,该异常未包含在 try 块中。

new ImageIcon(new URL(imageUri))
于 2009-10-10T14:16:26.153 回答
1

使用 ImageIcon 加载图像太棒了 1998 年。你想要ImageIO.read()

于 2009-10-11T00:47:07.440 回答
0

如果确实从 getImage() 抛出异常,您的代码应该捕获它。安全异常是异常。你在某个地方弄错了。例如,将 ImageIcon 构造函数放在 try 下。如果没有帮助,请尝试

catch( Throwable th )

虽然这是一个坏习惯。记录后至少尝试重新抛出它(或包装器异常)。

于 2009-10-10T14:14:47.433 回答
0

由于 ImageIcon 非常老派,并且产生了一个新线程(我不想要),我的解决方案如下:

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;
}

现在可以优雅地处理重定向、死链接等的任何问题。

于 2009-10-11T14:24:53.427 回答
0

这是一个旧线程 - 但我想添加一个替代答案,因为我在遇到同样的问题并点击这篇文章后得到了它。

因为我不想向我的应用程序添加更多依赖项(=javax),所以我使用此处建议的解决方案来获取位图,然后在这种情况下使用setImageBitmap , SecurityException被捕获

于 2015-06-04T09:47:16.657 回答