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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With