In an attempt to add some parameter validation and correct usage semantics to our application, we are trying to add correct exception handling to our .NET applications.
My question is this: When throwing exceptions in ADO.NET if a particular query returns no data or the data could not be found, what type of exception should I use?
Psuedocode: (read, don’t scrutinize the semantics of the code, I know it won’t compile)
public DataSet GetData(int identifier) { dataAdapter.Command.Text = 'Select * from table1 Where ident = ' + identifier.toString(); DataSet ds = dataAdapter.Fill(ds); if (ds.table1.Rows.Count == 0) throw new Exception('Data not found'); return ds; }
The MSDN guidelines state:
Consider throwing existing exceptions residing in the System namespaces instead of creating custom exception types.
Do create and throw custom exceptions if you have an error condition that can be programmatically handled in a different way than any other existing exceptions. Otherwise, throw one of the existing exceptions.
Do not create and throw new exceptions just to have your team’s exception.
There is no hard and fast rule: but if you have a scenario for treating this exception differently, consider creating a custom exception type, such as DataNotFoundException as suggested by Johan Buret.
Otherwise you might consider throwing one of the existing exception types, such as System.Data.DataException or possibly even System.Collections.Generic.KeyNotFoundException.