gpt4 book ai didi

java - instanceof 失败时的适当异常

转载 作者:行者123 更新时间:2023-12-02 01:53:35 24 4
gpt4 key购买 nike

当instanceof失败时,什么是适当的异常。像这样的事情:

if (user instanceof CustomerModel)
{
some logic...
}
else
{
throw new ClassCastException("Current user is not of type Customer");
}
}

我原本打算使用 ClassCastException,但我不能 100% 确定它在这种情况下是一个好的选择。

最佳答案

就像 Eran 所说,如果您只想要一个“行业标准”ClassCastException,只需尝试强制转换它,而不是使用 instanceof。如果您想要自定义异常,那么,这取决于您的意图。我们需要更多有关您想要的信息,以便提供更好的示例。我只是举一个随机的例子。

例如,如果您打算验证和转换方法参数或失败并显示自定义错误消息,我通常使用此方法:

public static <T, S extends T> S requireType(Class<S> type, T actual, String varName) {
requireNonNull(actual, varName);
if (!type.isInstance(actual))
throw new IllegalArgumentException('\'' + varName + "' must be of type " +
type.getName() +": " + actual.getClass());
//noinspection unchecked // It is just checked
return (S)actual;
}

那些可怕的通用参数会自动处理,例如:

FirmwarePacket castPacket = requireType(FirmwarePacket.class, packet, "packet");

关于java - instanceof 失败时的适当异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52623318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com