从catch块抛出多个异常的最佳方法

时间:2019-10-24 08:34:01

标签: java java-8

我正在为一个项目编写一些异常处理,在这些项目中,我必须根据catch块中的错误代码抛出异常。我是通过以下方式完成的:

public BankStatistics fetchBankStatistics(final Customer id) {
    final BankStatistics bs= this.bankStatService.fetchStatDetails(id);
    return bs;
} catch (final StaticticsProcessingexception ex) {
    if (ex.getErrorCode().equals("STAT-102")) {
      // log the error
      throw new MyNewCustomException(ERROR.INVALID_CUST_ID)
    }
    if (ex.getErrorCode().equals("STAT-103")) {
      // log the error
      throw new MyNewCustomException(ERROR.CUST_DOES_NOT_EXIST)
    }
    if (ex.getErrorCode().equals("STAT-104")) {
      // log the error
      throw new MyNewCustomException(ERROR.CUST_NOT_AUTHENTICATED)
    }
    return null;
}

上面的代码可以编译,但是我不知为何不喜欢从catch块返回null的想法。如果上面的代码是处理这种情况的最佳方法,或者还有其他方法,您是否可以提出建议?

3 个答案:

答案 0 :(得分:1)

在这种情况下,为什么不扔ex?

答案 1 :(得分:1)

您可能会使用空消息引发YourNewCustomException。

throw new MyNewCustomException();

答案 2 :(得分:1)

在这种情况下,我提供以下观点。我建议将错误代码映射作为键,将其他详细信息作为值。例如,您可以像这样维护。

Map<String,String> errMap = new HashMap<>();
errMap.put("STAT-102",ERROR.INVALID_CUST_ID);
errMap.put("STAT-103",ERROR.CUST_DOES_NOT_EXIST);
errMap.put("STAT-104",ERROR.CUST_NOT_AUTHENTICATED);

这样做的好处是,如果在异常块中可以这样简单地编写,则无需编写多个。

catch (final StaticticsProcessingexception ex) {
      throw new MyNewCustomException(errMap.get(ex.getErrorCode()))
}

正如开曼爵士所建议的那样,除了基于业务需求的uup之外,还可以引发IllegalArgumentException,还可以创建自己的异常类,并可以通过处理错误来引发它。

相关问题