Search code examples
javaconstructortry-catchfinal

Detecting if a final is blank in a constructor


I'm trying to create an enum for final Images, where the variable 'image' would be loaded from a file. If an IOException occurs, I want 'image' to be set to null. However, according to the compiler, 'image' may or may not be set when the catch block runs.

public enum Tile {
    GROUND("ground.png"), WALL("wall.png");
    final Image image;
    Tile(String filename) {
        try {
            image = ImageIO.read(new File("assets/game/tiles/" + filename));
        } catch (IOException io) {
            io.printStackTrace();
            image= null; // compiler error 'image may already have been assigned'
        }
    }
}

Final variables need to be set in the constructor, so if the image for some reason cannot be read, it has to be set to something. However, there's no way to tell whether or not image has actually been set. (In this case, the catch block only will run if no image is set, but the compiler says that it may have been set)

Is there a way for me to assign image to null in the catch block only if it hasn't been set?


Solution

  • Here is the solution I ended up using. It adds a method so that the code return if the ImageIO class does find an image, leaving no chance for the catch statement to be called.

    public enum Tile {
        GROUND("ground.png"), WALL("wall.png");
        final Image image;
        Tile(String filename) {
            image = getImage(filename);
        }
        Image getImage(String filename) {
            try {
                return ImageIO.read(new File("assets/game/tiles/" + filename));
            } catch (IOException io) {
                io.printStackTrace();
                return null;
            }
        }
    }
    

    However, this isn't really a way to detect a blank final variable. I'm hoping to see if there's a way to set a final variable inside a try/catch without going around the issue using temporary variables.