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?