-2

Code that triggers "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();
            }
        }

And so I removed the catch statement involving the error:

        try {
            try {
                img = ImageIO.read(new File("target.png"));
                String imgpath = "target.png";
            } catch (IOException e) {
                e.printStackTrace();
            }
        } finally {
            if (img != null) {
                width = img.getWidth();
                height = img.getHeight();
            }
        }

And now its triggering the error it said wouldn't trigger: "javax.imageio.IIOException: Can't read input file!"

What am I doing wrong

GR_ Gamer
  • 7
  • 1
  • 1

1 Answers1

0

You are making this more complicated than it needs to be.

Just check for the existence of the first file:

File imageFile = new File("target.png");
if (!imageFile.canRead()) {
    imageFile = new File("target.jpg");
}

try {
    img = ImageIO.read(imageFile);
} catch (IOException e) {
    throw new RuntimeException("Couldn't read target.png or target.jpg", e);
}

Unless you really believe your application will look and act properly without that image, the correct course of action when catching that exception (and most exceptions) is to stop what you’re doing by letting the exception propagate. Wrapping it in another exception is usually an effective way to do that.

VGR
  • 40,506
  • 4
  • 48
  • 63