You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java枚举valueOf空校验与异常处理优化:如何避免重复抛出异常

代码优化方案

方案1:预缓存枚举合法值,完全避免异常捕获(更推荐)

该方案规避了用异常做业务流程控制的坏实践,性能和可读性更优,全程仅一处抛出异常:
首先在当前类中预定义枚举合法名称的静态集合:

private static final Set<String> VALID_USER_NAMES = Arrays.stream(User.values())
        .map(Enum::name)
        .collect(Collectors.toUnmodifiableSet());

优化后的业务方法:

private UserContext getContext(String name) {
    boolean isBlank = StringUtils.isBlank(name);
    if (isBlank || !VALID_USER_NAMES.contains(name.toUpperCase())) {
        throw new IllegalArgumentException(isBlank ? 
            "name cannot be Null or empty" : 
            "name is not in the list of given names: " + name);
    }
    return map.get(User.valueOf(name.toUpperCase()));
}

方案2:保留原有逻辑,合并异常抛出分支

如果不想额外缓存枚举集合,可以收拢所有异常处理逻辑,仅在统一位置抛出一次异常:

private UserContext getContext(String name) {
    try {
        if (StringUtils.isBlank(name)) {
            throw new IllegalArgumentException();
        }
        return map.get(User.valueOf(name.toUpperCase()));
    } catch (IllegalArgumentException | NullPointerException e) {
        String errorMsg = StringUtils.isBlank(name) ? 
            "name cannot be Null or empty" : 
            "name is not in the list of given names: " + name;
        throw new IllegalArgumentException(errorMsg);
    }
}

内容的提问来源于stack exchange,提问作者user641887

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 17:12:00