在toString方法中抛出两个NullPointerExceptions

use*_*395 0 java exception throw

如何NullPointerException以相同的方法抛出两个?这就是我现在所拥有的,但第二次投掷导致错误"无法访问的声明"

public String toString() {
    if (rank == null || suit == null) {
        throw new NullPointerException ("Rank cannot be null");
        throw new NullPointerException ("Suit cannot be null");
    }
    return rank + suit;
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*yan 7

您不能一次抛出多个异常.此外,您不应该从类似的方法抛出异常toString()(相反,如果构造无效,则在创建对象时抛出异常).对于这样的事情,只是为遇到的第一个错误抛出一个异常.

构造此代码的更好方法是:

 public class Card {
    private final Rank rank;
    private final Suit suit;

    public Card(Rank rank, Suit suit) {
       this.rank = Preconditions.checkNotNull(rank);
       this.suit = Preconditions.checkNotNull(suit);
    }

    public String toString() {
      return "Card(rank=" + rank + ",suit=" + suit + ")";
    }
 }
Run Code Online (Sandbox Code Playgroud)

在这里,我假设你使用Preconditions.来自Guava库的checkNotNull()来简化检查.