문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top