Java Exception Handling in Parsers

Let's say we have a simple parser like this:

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) {
        return museum;


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


source to share

1 answer

Parser cannot do anything about the exception, so the parser throws an exception and cannot give the expected result. Someone from the outside has to deal with this.

In particular, it shouldn't return null

, as this would result in a bunch of null checks in the calling code (which you can easily forget to put or due to the lack of documentation on your implementation, I just don't know if I should check null

without seeing the code ). This is one of the problems that Java exceptions should have solved. By declaring a check-exception in the method signature, you are using your parser's users to deal with things that might not be of value.



All Articles