返回空而不是null

时间:2018-10-09 19:54:27

标签: java exception null

我有方法搜索异常

ValidationException(String operation) {
    super("Not valid for operation " + checkOperation(operation));
}

检查操作的方法

private static String checkOperation(String operation) {
    if (operation != null)
        return operation;
    else
        return null;
}

如果第一个方法开始工作并且operation == null,我们将显示消息“无效操作无效”。但是它必须是“对操作无效”。什么需要写而不是return null

1 个答案:

答案 0 :(得分:5)

将空格放入checkOperation的返回值中:

if (operation != null)
    return " " + operation;
else
    return "";

然后像这样调用:

super("Not valid for operation" + checkOperation(operation));
                           // ^ remove the space here

尽管我认为最好提供两个构造函数重载:

  • 不执行任何操作(并构造消息Not valid for operation)的人;
  • 另一个执行一个操作(并构造消息Not valid for operation whatever)。