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

Java返回枚举的方法异常时打印错误并返回值的规范处理方案

问题优化方案

当前代码存在编译错误,catch分支没有定义返回值,无法正常编译。以下是3种符合Java开发规范的处理方式,均不需要返回null,也能避免程序崩溃:

方案1:新增UNKNOWN枚举值(最推荐)

在Direction枚举中新增一个UNKNOWN枚举项,匹配失败时直接返回该值,完全避免空值,后续不需要额外非空校验,只要判断返回值是否为UNKNOWN即可做对应处理。
优化后的代码示例:

// 先修改Direction枚举,新增UNKNOWN项
enum Direction {
    NORTH, SOUTH, WEST, EAST, UNKNOWN
}

public static Direction getDirection(String direction) {
    // 提前预编译正则,避免每次调用都编译,提升性能
    final Pattern NORTH_PATTERN = Pattern.compile("go\\s+[n]|go\\s+north|north|[n]");
    final Pattern SOUTH_PATTERN = Pattern.compile("go\\s+[s]|go\\s+south|south|[s]");
    final Pattern WEST_PATTERN = Pattern.compile("go\\s+[w]|go\\s+west|west|[w]");
    final Pattern EAST_PATTERN = Pattern.compile("go\\s+[e]|go\\s+east|east|[e]");
    try {
        String lowerDirection = direction.toLowerCase();
        if (NORTH_PATTERN.matcher(lowerDirection).matches()) {
            return NORTH;
        } else if (SOUTH_PATTERN.matcher(lowerDirection).matches()) {
            return SOUTH;
        } else if (WEST_PATTERN.matcher(lowerDirection).matches()) {
            return WEST;
        } else if (EAST_PATTERN.matcher(lowerDirection).matches()) {
            return EAST;
        } else {
            System.out.println("Unknown Command");
            return UNKNOWN;
        }
    } catch (NullPointerException e) { // 处理输入为null的情况
        System.out.println("Input direction can not be null");
        return UNKNOWN;
    }
}

适用场景:调用方不需要感知具体错误原因,只需要区分合法/非法输入即可,代码侵入性最低。

方案2:返回Optional

Java 8+ 支持的标准空安全处理方式,显式告知调用方该方法可能返回空值,强制调用方做空处理,避免隐式空指针风险。
代码示例:

public static Optional<Direction> getDirection(String direction) {
    final Pattern NORTH_PATTERN = Pattern.compile("go\\s+[n]|go\\s+north|north|[n]");
    final Pattern SOUTH_PATTERN = Pattern.compile("go\\s+[s]|go\\s+south|south|[s]");
    final Pattern WEST_PATTERN = Pattern.compile("go\\s+[w]|go\\s+west|west|[w]");
    final Pattern EAST_PATTERN = Pattern.compile("go\\s+[e]|go\\s+east|east|[e]");
    try {
        String lowerDirection = direction.toLowerCase();
        if (NORTH_PATTERN.matcher(lowerDirection).matches()) {
            return Optional.of(NORTH);
        } else if (SOUTH_PATTERN.matcher(lowerDirection).matches()) {
            return Optional.of(SOUTH);
        } else if (WEST_PATTERN.matcher(lowerDirection).matches()) {
            return Optional.of(WEST);
        } else if (EAST_PATTERN.matcher(lowerDirection).matches()) {
            return Optional.of(EAST);
        } else {
            System.out.println("Unknown Command");
            return Optional.empty();
        }
    } catch (Exception e) {
        System.out.println("Input error: " + e.getMessage());
        return Optional.empty();
    }
}

调用方可以直接用Optional的链式API处理,示例:

// 匹配失败时返回默认值
Direction dir = getDirection("north").orElse(Direction.UNKNOWN);
// 仅匹配成功时执行逻辑
getDirection("xxx").ifPresent(dir -> {
    // 处理合法方向的业务逻辑
});

方案3:向上抛出异常,由上层统一处理

如果非法输入属于需要上层感知的业务异常,就不要在方法内部捕获异常,遵循单一职责原则,解析方法只负责解析逻辑,错误处理交给上层调用方实现。
代码示例:

public static Direction getDirection(String direction) throws IllegalArgumentException {
    final Pattern NORTH_PATTERN = Pattern.compile("go\\s+[n]|go\\s+north|north|[n]");
    final Pattern SOUTH_PATTERN = Pattern.compile("go\\s+[s]|go\\s+south|south|[s]");
    final Pattern WEST_PATTERN = Pattern.compile("go\\s+[w]|go\\s+west|west|[w]");
    final Pattern EAST_PATTERN = Pattern.compile("go\\s+[e]|go\\s+east|east|[e]");
    if (direction == null) {
        throw new IllegalArgumentException("Input direction can not be null");
    }
    String lowerDirection = direction.toLowerCase();
    if (NORTH_PATTERN.matcher(lowerDirection).matches()) {
        return NORTH;
    } else if (SOUTH_PATTERN.matcher(lowerDirection).matches()) {
        return SOUTH;
    } else if (WEST_PATTERN.matcher(lowerDirection).matches()) {
        return WEST;
    } else if (EAST_PATTERN.matcher(lowerDirection).matches()) {
        return EAST;
    } else {
        throw new IllegalArgumentException("Unknown Command: " + direction);
    }
}

上层调用时统一捕获处理:

try {
    Direction dir = getDirection(inputStr);
    // 处理正常业务逻辑
} catch (IllegalArgumentException e) {
    System.out.println(e.getMessage());
    // 执行异常降级逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 00:48:05