Frage

Which exception should be thrown by a method that accepts multiple arguments when the arguments given are invalid when given together?

As an example, consider

public Bar DoSomething(Foo f1, Foo f2)
{
  //implementation...
}

where completing the operation is contingent upon some relationship or similarity between f1 and f2 (if arrays/collections, they must be the same size; if athletes, they must be on the same team/opposing teams; etc.).

Each argument is a valid argument for the operation, but they are not valid together. Example:

public MatchResult PlayMatch(Player a, Player b)
{
  if(a.Team == b.Team)
  {
    //Throw exception here, since players must be on different teams
  }

  //Play match, determine winner
}

Throwing an ArgumentException seems incorrect, since it implies that one of the arguments is invalid rather than that the pair of arguments together is invalid.

War es hilfreich?

Lösung

You don't have to necessary throw an exception. In my opinion, this even should not throw an exception because is a deep part of your matching logic. I would just let matching fail (return zero or whatever you do) instead and mentioned this fact in documentation - something like "Compares two players from different teams." which implies that comparing players from the same team will result in fail.

Andere Tipps

ArgumentException would make sense here, as there is something wrong with the arguments being passed in. You can always add a message to your throw statement:

throw new ArgumentException("Players can't be on the same team!");

It's probably not a good idea to throw an exception here if the user did something wrong. I personally think exceptions should actually catch cases a user can't control (like a file read failing halfway) so you can fail the program gracefully. You can do is just display some sort of error message, return null, and force the user to pick teams again:

public MatchResult PlayMatch(Player a, Player b)
{
    if(a.Team == b.Team)
    {
        MessageBox.Show("Players must be on different teams!");
        return null;
    }

  //Play match, determine winner
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top