移除提示不可达的IIOException捕获块后触发该异常,求排查
问题解析:IIOException相关异常处理误区
问题背景
最初编写的代码触发IDE提示:Unreachable catch block for IIOException. This exception is never thrown from try statement,原代码如下:
int width = 0, height = 0; BufferedImage img = null; try { try { img = ImageIO.read(new File("target.png")); String imgpath = "target.png"; } catch (IOException e) { e.printStackTrace(); } } catch (javax.imageio.IIOException e) { try { img = ImageIO.read(new File("target.jpg")); String imgpath = "target.jpg"; } catch (IOException f) { f.printStackTrace(); } } finally { if (img != null) { width = img.getWidth(); height = img.getHeight(); } }
移除外层的IIOException catch块后,却看到输出了javax.imageio.IIOException: Can't read input file!,疑惑问题出在哪里。
原因分析
- 异常层级关系:
javax.imageio.IIOException是IOException的子类,内层的catch (IOException e)已经能捕获所有IO类异常(包括IIOException),所以外层的catch (IIOException)永远不会被执行,IDE才会提示“不可达”。 - 异常来源:修改后看到的
IIOException并不是程序未捕获的报错,而是内层catch块中e.printStackTrace()打印的异常信息——也就是说异常已经被捕获处理了,只是你看到了打印的栈信息而已。 - 冗余变量问题:原代码内层定义的
imgpath是局部变量,外层代码完全无法访问,属于无效代码。
修正后的代码
简化嵌套逻辑,实现“先读png,失败则读jpg”的需求:
int width = 0, height = 0; BufferedImage img = null; String imgpath = null; // 在外层定义路径变量,方便后续使用 // 先尝试读取PNG文件 try { img = ImageIO.read(new File("target.png")); imgpath = "target.png"; } catch (IOException e) { // PNG读取失败,尝试读取JPG try { img = ImageIO.read(new File("target.jpg")); imgpath = "target.jpg"; } catch (IOException ex) { ex.printStackTrace(); } } finally { if (img != null) { width = img.getWidth(); height = img.getHeight(); } }
修正说明
- 去除了不必要的嵌套try-catch,逻辑更直观
- 把
imgpath变量移到外层,确保后续代码可以访问到实际使用的图片路径 - 保持了“优先读PNG,失败则降级读JPG”的业务逻辑
- 异常捕获逻辑更合理,避免了不可达代码的问题
内容的提问来源于stack exchange,提问作者GR_ Gamer
相关产品推荐
相关产品推荐

