Java 方法包含另一个抛出异常的方法

Java method contains another method that throws exception

我有 public 方法 add(String) 调用私有方法 inspectSequence(String) 来检查字符串是否有效。

这个方法 returns 数组如果传递 String 是有效的,如果它无效则方法抛出 IllegalArgumentException

下一个代码

public void add(String sequence) throws IllegalArgumentException{
  inspectSequence(sequence);
}

private int[] inspectSequence(String sequence){
  int[] array;
  //some actions
  if(<some condition>) throw new IllegalArgumentException("description");
  return array;
}

所以在某些情况下,当将无效的 String 传递给 add 方法时,下一个输出将是:

java.lang.IllegalArgumentException: description
at inspectSequence
at add

但我不想让用户知道私有 inspectSequence 方法,因为这是实现细节,对吗?

那么在这种情况下我能做什么?在这里抛出未经检查的异常是个好主意吗?

inspectSequence 方法中抛出异常是个好主意,或者我应该 return null 当提供的 String 无效然后检查 returned 导致 add 方法并根据它抛出或不抛出异常?

But I don't want user to know about private inspectSequence method because this is realization detail, right?

我会说不。的确,您不希望用户(在该上下文中意味着有人调用代码)"know" 了解 inspectSequence() 等内部方法。使用 "know" 我的意思是能够调用、依赖等

知道可能会抛出异常,以及在什么情况下调用者应该知道的事情,知道确切的位置抛出不是必需的,但不会造成伤害。

当然,您可以在调用方法中捕获该异常并抛出另一个异常,但这只会丢失信息并可能使代码更难 debug/maintain,因为信息 where 不接受的输入将丢失给调用者。

So what I can do in that case? Is it a good idea to throw unchecked exception here?

这取决于该异常是应该在运行时处理还是修复。

假设调用者需要知道序列无效并且应该适当地处理该信息,例如向最终用户显示一些信息。在那种情况下,最好抛出一个描述这种情况的已检查异常。

另一方面,如果输入违反了方法的约定,即输入序列应该永远不会无效(否则是编程错误),那么IllegalArgumentException 没问题 - 将 null 传递给不需要 null 参数的方法的情况。

And is a good idea to throw exception inside inspectSequence method or I should return null when supplied String isn't valid and then check returned result in add method and depending on it throw or not throw exception?

我会说不。返回 null 然后在调用方法中处理它 在某些情况下可能 是一种合理的方式(例如,如果您有不同的调用者以不同方式处理 null )但您的情况是 none那些。这会使代码更复杂,因此更难阅读和维护,尤其是因为 null 可能具有多种含义,您必须在这种情况下定义这些含义。

您可以捕获 IllegalArgumentException 并抛出您自己的异常。

public void add(String sequence) throws MyCustomException {
    try {
        inspectSequence(sequence);
    } catch (IllegalArgumentException e) {
        throw new MyCustomException("more readable cause that hides internals");
    }
}