什么是正确的.NET异常抛出时尝试插入重复的对象到一个集合?

什么是正确的.NET异常抛出时尝试插入重复的对象到一个集合?

问题描述:

我有一个具有一个属性AssignedSoftware,这是一个集合的资产的对象。

I have an Asset object that has a property AssignedSoftware, which is a collection.

欲确保同一块软件的没有被分配给资产超过一次。在添加方法我检查,看看是否已经软件存在,如果是这样,我想抛出一个异常。

I want to make sure that the same piece of Software is not assigned to an Asset more than once. In Add method I check to see if the Software already exist, and if it does, I want to throw an exception.

有没有办法,我应该抛出一个标准的.NET异常?还是最佳实践要求我创建自己的自定义异常?

Is there a standard .NET exception that I should be throwing? Or does best practices dictate I create my own custom exception?

从类库设计指南中的错误(的http://msdn.microsoft.com/en-us/library/8ey5ey87(VS.71)。 ASPX ):

From the Class Library design guidelines for errors (http://msdn.microsoft.com/en-us/library/8ey5ey87(VS.71).aspx):

在大多数情况下,使用预定义的异常类型。只有在编程方案,在那里你期望你的类库的用户基础上,异常类型本身赶上这一新类型的异常和执行方案行动定义新的异常类型。这是代替解析异常串,这将性能和维护产生负面影响的

In most cases, use the predefined exception types. Only define new exception types for programmatic scenarios, where you expect users of your class library to catch exceptions of this new type and perform a programmatic action based on the exception type itself. This is in lieu of parsing the exception string, which would negatively impact performance and maintenance.

...

引发ArgumentException或创建若无效参数传递或检测到从这个类派生的异常。

Throw an ArgumentException or create an exception derived from this class if invalid parameters are passed or detected.

扔InvalidOperationException异常,如果一个属性set访问或方法调用不恰当的给予对象的当前状态。

Throw the InvalidOperationException exception if a call to a property set accessor or method is not appropriate given the object's current state.

这似乎是一个对象状态无效的情景给我,所以我会选择InvalidOperationException异常过度的ArgumentException:该参数是有效的,但不是在对象的生命这一点

This seems like an "Object state invalid" scenario to me, so I'd pick InvalidOperationException over ArgumentException: The parameters are valid, but not at this point in the objects life.