Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java exception handling in parsers

Let's say we have such a simple parser:

public class ResourceManager {

    private final static Logger LOG = Logger.getLogger(ResourceManager.class);

    public Museum parseJSONFile(String filePath) /*throws IOException ???? */ {
        Museum museum = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();

            museum = objectMapper.readValue(new File(filePath), Museum.class);
        } catch(IOException e) {
            LOG.error(e);
        }
        return museum;
    }
}

Should the exception be caught in method or in the calling code? Which variant is better?

like image 449
StasKolodyuk Avatar asked Feb 11 '23 20:02

StasKolodyuk


1 Answers

Parser can't do anything with exception, so that's an exceptional situation for a parser and it can't produce any expectable result. Someone from the outside should handle it.

In particular, it should not return null as it will result in bunch of null-checks in calling code (which you can easily forget to put, or due to the lack of documentation on your implementation I just don't know whether I have to check for null without seeing the code). This is one of the problems that exceptions in Java were intended to solve. By declaring checked-exception in method signature, you're enforcing users of your parser to deal with fact that value might not come.

like image 83
Dmitry Zaytsev Avatar answered Feb 14 '23 09:02

Dmitry Zaytsev