简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM