Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return statement in case of exception

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.

like image 657
Russiancold Avatar asked Dec 24 '22 17:12

Russiancold


1 Answers

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.

like image 159
GhostCat Avatar answered Jan 01 '23 22:01

GhostCat