Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exception type should be thrown when trying to add duplicate items to a collection? [closed]

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?

like image 790
klashar Avatar asked Aug 14 '09 20:08

klashar


People also ask

What is duplicate key exception?

The DuplicateKeyException exception is thrown if an entity EJB object or EJB local object cannot be created because an object with the same key already exists. This exception is thrown by the create methods defined in an entity bean's home or local home interface.


2 Answers

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

like image 169
Pavel Minaev Avatar answered Sep 21 '22 12:09

Pavel Minaev


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

like image 38
amarnath chatterjee Avatar answered Sep 19 '22 12:09

amarnath chatterjee