是否可以在此处从 header 中删除 "throw IllegalArgumentException"?

Is it possible to remove "throw IllegalArgumentException" from header here?

我想知道我是否可以删除此方法 header 中的 IllegalArgumentException,将其放在方法的 body 中,并且仍然以相同的方式工作?

谢谢!

public Card(int value, String suit) throw IllegalArgumentException {
    LinkedList<String> suits = new LinkedList<>(Arrays.asList("spades", "hearts", "diamonds", "clubs"));//all suits in the lower case
    if(value >= 1 && value <= 13 && suits.contains(suit.toLowerCase())) {
        this.value = value;
        this.suit = suit;
    } else {
        throw new IllegalArgumentException("Illegal suit-value combination");//throw exception in case value or suit is wrong
    }
}

您不需要在方法声明中显式声明 RuntimeException。由于 IllegalArgumentExceptionRuntimeException,您可以将其删除。

来自offical documentation

Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).

您可以在该方法的 JavaDoc 部分提及它。这会向消费者提示任何抛出的未经检查的异常。将此信息间接附加到参数也很常见。

/**
  * @throws IllegalArgumentException if the suite combination is illegal
  */

/**
  * @param myParam the param, must not be null
  */

参数验证通常包括在一个参数不符合要求时抛出 IllegalArgumentException。由于那些在 JavaDoc 中列出(这里,not null),如果他通过 null,那是程序员的错。