What .NET exception is thrown for an invalid database state?

I am writing a data access code, and I want to check the potentially โ€œinvalidโ€ states of the data in the database. For example, I am returning a widget from a database, and I am only expecting it. If I get two, I want to throw an exception. Despite the fact that referential integrity should prevent this, I do not want to depend on database administrators who never change the scheme (to clarify this, if the primary key constraint is removed and I get cheated, I want to quickly and clearly break it down).

I would like to use a System.IO.InvalidDataException exception, except that I am not dealing with a file stream, so it is misleading. As a result, I came across a common application. Anyone have a better idea?

+7
c # exception-handling
source share
4 answers

InvalidDataException seems to me pretty reasonable:

  • The name is perfect
  • The description fits quite reasonably, given that it effectively "flows" data from the database
  • Nothing in the description mentions files, so I will not worry about this side of things.

You effectively deserialize data from the store. It happens to be RDBMS, but it is relatively unimportant. The data is invalid, so an InvalidDataException fits well.

In other words, if you are loading data from a file, are you InvalidDataException ? Assuming you should, why does it matter where the data comes from, in terms of the exception that is selected?

+15
source share

If you need an exception that accurately describes the situation you're dealing with, why not make your own exception?

Just inherit it from System.Exception.

+6
source share

I may be tempted to use one of the following:

InvalidConstraintException
NotSupportedException
Overflowexception

Or just go ahead and create your own: TooManyRowsException

+1
source share

You can write a custom exception if you don't find a suitable standard exception ...

But you say:

Although referential integrity should prevent this, I do not want to depend on database administrators to never change the schema.

When someone changes the database schema, the changes are quite large, and you will also have to make some changes to the application code / data access code ...

0
source share

All Articles