Return statement on exception
What is the correct way to use it return
in the following method?
public Image getImage() {
try {
Image img = ImageIO.read(new File(URL));
return img;
} catch (IOException e) {
e.printStackTrace();
}
}
The IDE is asking me to return something at the end. But I do not know what I should return to.
source to share
Correct answer: depends on your requirements. Possible options:
If the caller of this method can deal with a null response, return null from the catch block. Alternatively, you can return a "special" predefined image object in this case. It might be slightly better, since returning null is always the first step that throws Nullpointerexceptions elsewhere.
Or you catch and roll some kind of unchecked exception. Or you don't catch at all and you add "throws IoException" to the method signature.
When you are using Java 8, the simple solution is to use the new Optional class.
source to share
If your method catches an exception and doesn't throw anything, it should return some default value (possibly null) after the try-catch block.
I think you shouldn't catch the exception. This way, you only return a value if the operation ImageIO.read
does not throw an exception. You will of course have to declare that your method throws IOException
, since it is a checked exception.
This will force the caller of your method to process IOException
(or let its own caller handle it).
source to share