Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception for missing data

Tags:

c#

exception

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?

like image 545
Elz Avatar asked Sep 21 '09 07:09

Elz


People also ask

What is data exception?

If we find that something in your data is not correct and we can't start producing your order, we raise an “Exception”. Possible reasons are: the data is not complete – e.g. the drill file is missing. the data is ambiguous – e.g. top and bottom layers are not clearly defined.

What is an exception in CS?

An exception occurs when a program's instructions are interrupted during execution. An error occurs within a method, which creates an object and passes it on to the runtime system as soon as possible. An exception handler is a block of code that contains exceptions.


2 Answers

As a rule of thumb, check the existing .NET framework exceptions for a suitable exception to throw before deriving your own. To answer your question directly, there is no "missing data" exception currently available to throw, but that doesn't mean there aren't suitable exceptions to cover your situation.

In your case, the humble InvalidOperationException may be suitable; this exception is thrown when you call a method on an object, but the object's state is not appropriate for the operation. Examples of this include calling methods on a closed stream and an enumerator that has passed the end of the collection. If the XML data is the internal state of an object, and a method call has discovered the bad data, InvalidOperationException is a good candidate.

If you are passing your XML data to a method, an ArgumentException, or one of its derivatives may be an appropriate choice. There is a small family of these exceptions, all indicating that an argument passed to a method is not as the method expected.

You will only want to create a custom exception when you want the exceptional circumstance to be handled differently from other exceptions. If you do choose to create your own exception, be sure to derive it from a higher exception than Exception, so that the nature of the exception is implied by the base class.

like image 171
Paul Turner Avatar answered Sep 18 '22 10:09

Paul Turner


There is also System.Data.ObjectNotFoundException class which you may consider.

Update: As of Entity Framework 6, this exception class' fully qualified name is System.Data.Entity.Core.ObjectNotFoundException.

See this question for further details on EF5->EF6 namespace changes.

like image 40
Kirill Kovalenko Avatar answered Sep 19 '22 10:09

Kirill Kovalenko