无法捕获异常

时间:2016-02-26 14:33:20

标签: java exception try-catch

以下代码会抛出NullPointerException未处理的try catch。为什么会这样,我该如何处理这个异常?

try
{
    URL url = MyTestApp.class.getResource("deliberately_bad_path/icon.png");
    Image img = Toolkit.getDefaultToolkit().createImage(url);
    ImageIcon icon = new ImageIcon(img);
} catch (Exception e)
{
    System.out.println("Okay it was an Exception");
    e.printStackTrace();
} catch (Throwable  e)
{
    System.out.println("Okay it was a throwable");
    e.printStackTrace();
} 

因此未捕获异常并显示以下输出:

  

取消图片的未捕获错误:
  显示java.lang.NullPointerException
    at sun.awt.image.URLImageSource.getConnection(Unknown Source)
    at sun.awt.image.URLImageSource.getDecoder(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)

1 个答案:

答案 0 :(得分:4)

错误原因很可能是您将空Url传递给Toolkit.createImage

图像加载由sun.awt.image.ImageFetcher完成。它在一个自己的线程中运行(实际上它是从Thread派生的)因此你的catch块没有捕获它的error