Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exception should be thrown by a .NET program if it encounters invalid data?

Tags:

.net

exception

Consider the following example: as part of configuration for my program the user supplies an XML file which should in essence describe an acyclic graph, but my program finds a graph when loading it. This is a critical error, the program cannot continue. What exception should be thrown?

Other examples include trying to load a file in some specific format (say JPEG), but encountering an error along the way; or receiving some data over the network from another 3rd party program which should be correct, but isn't.

In essence - you're parsing some kind of data stream and find an error in it which shouldn't be there and which means that the program cannot continue as expected. What is the right type of exception to throw here?

(Note: This shouldn't be an ArgumentXXXException because this data isn't passed as a parameter to a method).

like image 820
Vilx- Avatar asked Oct 29 '25 08:10

Vilx-


2 Answers

For at least some of your scenarios, System.IO.InvalidDataException would be a good fit.

For an XML file, the best approach is probably to validate against a predefined schema, in which case a System.Xml.Schema.XmlSchemaValidationException validation will be thrown.

like image 141
Nicole Calinoiu Avatar answered Oct 31 '25 22:10

Nicole Calinoiu


Create your own exception - I don't believe there is an exception class in the BCL that will describe exactly this scenario.

Perhaps a CyclicGraphFoundException?

like image 38
Oded Avatar answered Oct 31 '25 23:10

Oded



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!