Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which .NET exception to throw for invalid database state?

I am writing some data access code and I want to check for potentially "invalid" data states in the database. For instance, I am returning a widget out of the database and I only expect one. If I get two, I want to throw an exception. Even though referential integrity should prevent this from occurring, I do not want to depend on the DBAs never changing the schema (to clarify this, if the primary key constraint is removed and I get a dupe, I want to break quickly and clearly).

I would like to use the System.IO.InvalidDataException, except that I am not dealing with a file stream so it would be misleading. I ended up going with a generic applicationexception. Anyone have a better idea?

like image 879
jslatts Avatar asked Apr 13 '10 16:04

jslatts


People also ask

What is invalid data exception?

Remarks. An InvalidDataException is thrown when invalid data is detected in the data stream.

Which exception occurs whenever an invalid argument is used in a function call?

ArgumentException is thrown when a method is invoked and at least one of the passed arguments does not meet the parameter specification of the called method. The ParamName property identifies the invalid argument.


1 Answers

InvalidDataException seems pretty reasonable to me:

  • The name fits perfectly
  • The description fits pretty reasonably when you consider that it's effectively a data "stream" from the database
  • Nothing in the description mentions files, so I wouldn't be worried about that side of things

You're effectively deserializing data from a store. It happens to be an RDBMS, but that's relatively unimportant. The data is invalid, so InvalidDataException fits well.

To put it another way - if you were loading the data from a file, would you use InvalidDataException? Assuming you would, why should it matter where the data is coming from, in terms of the exception being thrown?

like image 180
Jon Skeet Avatar answered Nov 14 '22 05:11

Jon Skeet