简体   繁体   English

当没有对象与键相关联时,应该抛出什么异常?

[英]What exception should be thrown when there is no object associated with a key?

I have an API where I am checking whether there are any existing objects available for a given key. 我有一个API,用于检查给定密钥是否有任何现有对象。 If available, then update the existing object, otherwise create new object and save it. 如果可用,则更新现有对象,否则创建新对象并保存。

If there is a case in which the key is available, but no object is linked to it, which exception should be thrown? 如果存在密钥可用但没有对象链接的情况,应抛出哪个异常?

It really depends on how you want to build your API. 这实际上取决于您要如何构建API。 I think hhe first thing you need to decide is: should this exception be caught by caller or not necessarily? 我认为您需要决定的第一件事是:此异常是否应该被调用方捕获? In other words, is it a RuntimeException or not? 换句话说,它是否是RuntimeException

I guess that if you want to throw an exception, it's because your data model should not have empty / null objects for a given key. 我猜想如果您想引发异常,那是因为您的数据模型对于给定的键不应有空对象。 So, I would argue for an IllegalStateException or NoSuchElementException , which extends RuntimeException . 因此,我主张使用IllegalStateExceptionNoSuchElementException ,它扩展了RuntimeException It means that the caller is not forced to catch the exception. 这意味着不会强制调用方捕获异常。

If you want to force caller to catch the exception I would suggest you create your own exception that just extends Exception 如果要强制调用方捕获异常,建议您创建自己的异常,该异常仅扩展Exception


EDIT: 编辑:

For instance, a class named "MissingValueException" and defined as follow: 例如,一个名为“ MissingValueException”的类,其定义如下:

public class MissingValueException extends Exception {
    private static final long serialVersionUID = 1L;

    public MissingValueException(final String message) {
        super(message);
    }

    public MissingValueException(final String message, final Exception root) {
        super(message, root);
    }
}

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

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