What is the correct way of using return
in the following method?
public Image getImage() {
try {
Image img = ImageIO.read(new File(URL));
return img;
} catch (IOException e) {
e.printStackTrace();
}
}
IDE asks me to return something at the end. But I don't know what I'm supposed to return.
The correct answer is: depends on your requirements. Options are:
If the caller of this method could deal with a null answer, return null from the catch block. Alternatively, you could return a "special" pre-defined image object in that case. Might be a slightly better way - as returning null is always the first step to cause Nullpointerexceptions elsewhere.
Or, you catch and rethrow some unchecked exception. Or you don't catch at all and you add "throws IoException" to the signature of the method.
When you are using Java 8, the simple solution is to use the new class Optional.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With