Java 是否可以从标题中删除“throw IllegalArgumentException”?
我想知道我是否可以删除这个方法头中的IllegalArgumentException,将它放在方法体中,并且仍然以相同的方式工作 谢谢Java 是否可以从标题中删除“throw IllegalArgumentException”?,java,illegalargumentexception,Java,Illegalargumentexception,我想知道我是否可以删除这个方法头中的IllegalArgumentException,将它放在方法体中,并且仍然以相同的方式工作 谢谢 public Card(int value, String suit) throw IllegalArgumentException { LinkedList<String> suits = new LinkedList<>(Arrays.asList("spades", "hearts", "diamonds", "clubs"
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。由于IllegalArgumentException是一个RuntimeException,因此可以删除它 从: 运行时异常可能发生在程序中的任何地方,在典型的程序中,它们可能非常多。必须在每个方法声明中添加运行时异常会降低程序的清晰度。因此,编译器不要求您捕获或指定运行时异常,尽管您可以 您可以在方法的JavaDoc部分提到它。这将向使用者提供有关抛出的任何未检查异常的提示。将此信息间接附加到参数也是很常见的
/**
* @throws IllegalArgumentException if the suite combination is illegal
*/
/**
* @param myParam the param, must not be null
*/
参数验证通常包括在一个参数不满足要求时抛出IllegalArgumentException。因为这些都列在这里的JavaDoc中,而不是null,如果通过null,则是程序员的错 它应该被扔掉而不是扔进脑袋当你尝试它时发生了什么?谢谢,Snowy1803。@khelwood它仍然在运行,但我不知道如何测试它,看看它在不同的情况下是否能坚持,这就是为什么我想知道它是否只是sameThank你,我感谢你的帮助!