user5508946 user5508946 - 27 days ago 8
Java Question

Java - Why is this not allowed?

BufferedImage water;

try {
water = ImageIO.read(new File("src/icones/water.png"));

}
catch (IOException e)
{
System.out.println(e.getMessage());
System.exit(1);
}

images[0] = new BufferedImage[1];
images[0][0] = water;


It wont compile because "water might not be initialized".
If i understand correctly it is a bit stupid because if it is not initialized (try block fail) then the program stop (catch bloc) so it wont reach the line that create the problem.

Sure i can solve this by initalizing water to null or doing everything in the try but it feels wrong to me, is this the correct way to do it ?

Answer

System.exit is, for reasons which are hard to explain, treated by the compiler like a method which may return. Because of this, it believes it's possible to leave that catch block and use water before it's initialized.

You should probably just throw an exception throw new RuntimeException(e); after your System.exit call to make the compiler happy.