Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exception to throw when two values I expect to be equal are not equal? (C#)

I feel like this has to be a duplicate, but I've tried looking around and can't find what I'm looking for.

The example I'm working with starts with parsing an XML document. In this XML document the name of a person is stated in two different locations. Later in a different method, I need to use this person's name. I can use any of these two references to the person's name in the XML document since they are the same, or so I expect. I first want to check that they are indeed the same. If they are not equal for whatever reason, I feel like it would be best to throw an exception. Is there an exception for when two values that one would expect are equal are not in fact equal?

I considered ArgumentException, but I'm not sure if that's best since it specifies:

ArgumentException is thrown when a method is invoked and at least one of the passed arguments does not meet the parameter specification of the called method.

This isn't the case here since the arguments are fine, it's just that the value of one of the properties (i.e. the person's name) is not what I expect it to be.

I suppose the first question you might have is why do I want to throw an exception. Maybe it's not the best option, but I feel it should be done considering that the reason the two names do not match is because when the XML document was created one of the name-writes did not do its job correctly, which I'd probably want to know. I'm not experienced with error handling, so it's possible that this doesn't mean an exception should be thrown. Any advice would be appreciated.

like image 972
Drew Avatar asked Mar 11 '23 11:03

Drew


1 Answers

I first want to check that they are indeed the same. If they are not equal for whatever reason, I feel like it would be best to throw an exception.

You could use InvalidOperationException, since your operation expects the values to be equal. If the values are not equal, your operation is invalid.

You could also define your own exception. You can afterward customize your exception in regards of your situation / objects to compare.

like image 96
Etienne Faucher Avatar answered Mar 30 '23 01:03

Etienne Faucher