返回空而不是null

Men*_*tha 2 java null exception

我有方法搜索异常

ValidationException(String operation) {
    super("Not valid for operation " + checkOperation(operation));
}
Run Code Online (Sandbox Code Playgroud)

以及检查操作的方法

private static String checkOperation(String operation) {
    if (operation != null)
        return operation;
    else
        return null;
}
Run Code Online (Sandbox Code Playgroud)

如果第一个方法开始工作,operation == null我们有消息"无效操作null".但它必须是"无效的操作".什么需要写而不是return null

And*_*ner 5

将空格放入返回值checkOperation:

if (operation != null)
    return " " + operation;
else
    return "";
Run Code Online (Sandbox Code Playgroud)

然后调用如下:

super("Not valid for operation" + checkOperation(operation));
                           // ^ remove the space here
Run Code Online (Sandbox Code Playgroud)

虽然我认为最好提供两个构造函数的重载:

  • 一个不进行操作(并构造消息Not valid for operation);
  • 另一个接受一个操作(并构造消息Not valid for operation whatever).