Should application expect the unexpected when fetching data from database? Lets say that we have stored an enumeration value in a column (int or text). When we return values from database, we cast the value to enumeration type. What if someone has altered data in database manually, and broke data integrity, so our cast is failing?
Another example would be when a data type in c# is of less range that equivalent field in database. If anyone puts value in this value manually, lets say to database max value, then application would throw out of range exception.
Should we and how handle this exceptions?
Edit: Since most of the answers are similar, I am going to rephrase the question. It is implied that there is exception logging in the application. The problem is: when user queries for some data, and the data is corrupted (not from application CRUD operations, but outside), data conversion from database to model will fail, and user will get no data at all. Is it acceptable to have such a state in application, since the application itself didnt cause it?
Validating data would create a big slowdown on data fetching. Imagine that you need to check each decimal value if its out of range?
I always took it to be standard practice to place any database interaction code in the datalayer with in
try...catchblocks so that you can handle situations such as this in a civilised manner.I don’t check for every eventuality, but being able to log exceptions will prove useful when supporting your code in the long run.
In the case of a live system it’s always good to have such information especially when you can accuse a customer of fiddling with things that they shouldn’t have.
edit
As I said you can’t check for every eventuality, but you can trap exceptions caused by situations such as casting a value to an enum that doesn’t exist.
It isn’t really possible to check for values that are out of range, other than the extreme e.g. a field unexpectedly comes back as
DBNullor fails convertion from database datatype to model data type. In such a case handling the error and presenting the user with an error message or "VALUE UNKNOWN" type indicator should be okay.The problem here is that you have a user who is changing data without using your application.
You may already be implementing
IDataErrorInfoin your data model, specifically to validate user input, if not look here for an example, or maybe something similar.But you can’t really cope with ‘corrupted’ data being a valid value i.e. if your enum field was changed to one that was correct value wise but incorrect logically you wouldn’t know until you came to use it that it was wrong.
A pragmatic approach has to be taken as you rightly said validation of thousands or even just hundreds of values being retrieved from the database would have an unexceptable hit on performance.
But saying "There’s been an error, please contact your system administrator" or something similar is perfectly acceptable in my view.