简体   繁体   English

解析器中的Java异常处理

[英]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). 特别是,它不应该返回null因为它会导致调用代码中的大量空值检查(您很容易忘记放置,或者由于缺少有关您的实现的文档,我只是不知道是否必须检查null而不看代码)。 This is one of the problems that exceptions in Java were intended to solve. 这是Java中的异常旨在解决的问题之一。 By declaring checked-exception in method signature, you're enforcing users of your parser to deal with fact that value might not come. 通过在方法签名中声明checked-exception,您可以强制解析器的用户处理可能不会出现值的事实。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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