Search code examples
c#.netexceptionkeynotfoundexception

Should I throw a KeyNotFoundException for a database lookup?


I've got some code that, given an ID, returns an item from the database. If no item matches the given ID, is it appropriate to throw a KeyNotFoundException, or are such exceptions meant only for Dictionary types?


Solution

  • Depending on the framework you're using to access the database (ODBC, ADO.NET, etc.) there's likely a better alternative that the framework would throw.

    The System.Data namespace contains several such exceptions as examples: http://msdn.microsoft.com/library/system.data.

    Really, though, as long as you document what exception you're throwing and in what conditions it doesn't matter too much. Using something common is best because people may assume, but if they are reading documentation they will handle whatever exception you say would be thrown.