38

Following code should throw exception to prevent adding duplicate collection item.

ICollection<T> collection = new List<T>();

public void Add(T item)
{
    if (collection.Contain(item))
    {
          throw new SomeExceptionType()
    }

    collection.Add(item);
}

What standard exception type is the most appropriate?

Jay
  • 9,561
  • 7
  • 51
  • 72
klashar
  • 2,519
  • 2
  • 28
  • 38
  • 3
    Closest specific exception I found was [DuplicateNameException](https://msdn.microsoft.com/en-us/library/system.data.duplicatenameexception(v=vs.110).aspx) for databases ... which is just a bad idea for a `Collection`. Take home message: Anyone wanting more specific could _roll their own Exception_ – KCD Jul 17 '15 at 03:48

8 Answers8

48

Well, Dictionary<,>.Add() throws ArgumentException if such key already exists, so I guess this could be a precedent.

Pavel Minaev
  • 99,783
  • 25
  • 219
  • 289
12

Linq uses two more exceptions DuplicateNameException and DuplicateKeyException you can use these if you are using system.data assembly.

amarnath chatterjee
  • 1,942
  • 16
  • 15
6

ArgumentException would probably be the best. This is the exception thrown when an argument is invalid.

Brandon
  • 68,708
  • 30
  • 194
  • 223
4

I would use InvalidOperationException:

The exception that is thrown when a method call is invalid for the object's current state.

Since the validity of the argument's value is contingent upon the state of the object (that is whether or not collection.Contains(item) is true) I think this is the best exception to use.

Make sure that you add a good message to the exception that makes it clear what the problem was to the caller.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
  • 2
    IMHO, InvalidOperationException will confuse user because it used mostly to show unapropriate oparation sequence. For instance, reading from closed reader, etc. – klashar Aug 14 '09 at 20:42
3

ArgumentException would be the proper exception (Dictionary uses that exception as well)

cyberconte
  • 2,371
  • 4
  • 21
  • 27
2

I'd say InvalidOperationException, because it is not valid to add an object that's already in the collection

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • If it were a Dictionary this would be true, but it's not. – Brandon Aug 14 '09 at 20:38
  • 1
    There are collections that don't allow duplicates, AND dictionaries that allow them... in the poster's case he clearly doesn't want duplicates, or why would he want to throw an exception ? – Thomas Levesque Aug 14 '09 at 20:56
  • Sorry, I phrased that comment badly, I more meant to say that if the OP is using a collection that does allow duplicates, its not really an invalid operation. Its a "he doesn't consider this valid" thing. Also I'm not the one who downvoted this >_> I don't agree this is the best exception, but I don't think it would be wrong to use it. – Brandon Aug 14 '09 at 21:05
1
System.ArgumentException
Ben M
  • 22,262
  • 3
  • 67
  • 71
1

I would throw an ArgumentException. That's what the generic System.Collections.Generic.SortedList<> does in its Add method.

From the .NET Framework 2.0 code:

    public void Add(TKey key, TValue value)
    {
        if (key == null)
        {
            System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.key);
        }
        int num = Array.BinarySearch<TKey>(this.keys, 0, this._size, key, this.comparer);
        if (num >= 0)
        {
            System.ThrowHelper.ThrowArgumentException(System.ExceptionResource.Argument_AddingDuplicate);
        }
        this.Insert(~num, key, value);
    }
Paul Williams
  • 16,585
  • 5
  • 47
  • 82