variable name cannot be resolved but I have already created the variable

Viewed 43
try {
    try {
        Image img = ImageIO.read(new File("target.png"));
        String imgpath = "target.png";
        } catch (IOException e) {
        e.printStackTrace();}
    } finally {
        int width = img.getWidth();
        int height = img.getHeight();
    }
}

I have already created "img" in this line:

Image img = ImageIO.read(new File("target.png"));

But when I want to get the dimensions of "img" in these lines;

int width = img.getWidth();
int height = img.getHeight();

it gives me this error: img cannot be resolved

Could anyone tell me what I did wrong pls

1 Answers

The problem here is "img" is only defined in the inner "try" block. Try this:

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