是否可以从头部删除“抛出IllegalArgumentException”?

问题描述 投票:-1回答:1

我想知道我是否可以删除此方法的标头中的IllegalArgumentException,将它放在方法的主体中,并且仍然以相同的方式工作吗?

谢谢!

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
    }
}
java illegalargumentexception
1个回答
2
投票

您不需要在方法声明中明确声明RuntimeException。由于IllegalArgumentExceptionRuntimeException,你可以删除它。

来自offical documentation

运行时异常可以在程序中的任何地方发生,而在典型的程序中,它们可以非常多。必须在每个方法声明中添加运行时异常会降低程序的清晰度。因此,编译器不要求您捕获或指定运行时异常(尽管您可以)。

你可以在方法的JavaDoc部分提到它。这为消费者提供了任何未经检查的异常抛出的提示。将这些信息间接附加到参数也是很常见的。

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.