2

I have a standalone application that does data checking of flat files before they are imported into a SQL database.

In a context like this, does it make sense to throw a System.Data.ConstraintException? (The example is contrived.)

if(_keys.ContainsKey(key))
{
    throw new ConstraintException(string.Format("Uniqueness violated! " + 
        "This unique combination of '{0}' already found on line {1}", 
        GetUniquenessColumnList(), _keys[key] ));
}

ConstraintException's documentation states that it "represents the exception that is thrown when attempting an action that violates a constraint."

Is there a problem with using the built-in exception this way? Is there a better one to use? Should I build my own, even though this exception seems tailor-made to my situation?

neontapir
  • 4,698
  • 3
  • 37
  • 52

2 Answers2

3

I think you've answered your own question

...this exception seems tailor-made to my situation?

Why reinvent the wheel?

EDIT:

Check out this MSDN article: Choosing the Right Type of Exception to Throw

Consider throwing existing exceptions residing in the System namespaces instead of creating custom exception types.

...

Do not create and throw new exceptions just to have your team's exception.

Community
  • 1
  • 1
Nathan
  • 1,080
  • 7
  • 16
2

No, there's no problem with doing that. No need to create a new exception if a suitable one already exists.

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • Agree, though deriving a new (custom) class (maybe exposing some extra properties for more details about the exception, like a ViolatedKey) is also a (good, maybe second?) option. This would, for example, make "extracting" the "violated key (value)" easier because you wouldn't have to rely on getting it from the actual message(string). Just make sure you keep [YAGNI](http://en.wikipedia.org/wiki/You_ain't_gonna_need_it) in the back of your head when considering this option. – RobIII Jul 17 '12 at 23:25