Exception for missing data

Viewed 42221

I was wondering what kind of exception should one throw for missing data. For example if an xml node doesn't contain data. It would be easy to "throw new Exception(...)" but this is not recommended. Another option would be to create a new exception class like MissingDataException or InvalidDataException but isn't there a built-in exception class for this case?

8 Answers

For a general missing data scenario, where the data is referenced by a unique ID, then the KeyNotFoundException might be appropriate - e.g.

throw new KeyNotFoundException($"Expected record for key {key} not found.");

It is in the System.Collections.Generic namespace.

InvalidDataException actually exists. It's in the System.IO namespace. MSDN

IMO, it's more appropriate than ArgumentException or another boneheaded exception type.

Also, I strongly suggest that you use messages to describe which data is missing, what was the expected value, etc...

Related