I’m parsing a byte array, which is in effect a fix length record that is being sent on a message bus. If the data isn’t valid (garbled or doesn’t fit the spec for the record) then I want to throw an exception. Something like this:
public DomainObject ParseTheMessage(byte[] payload){
Validate(payload);//throws an exception if invalid
...do creation of domain object
}
Does anyone know if there is a good standard exception I can throw in these circumstances or should I just create my own specific exception?
You can just use
ArgumentException:As mentioned below by x0r, MSDN recommends only deriving from
ArgumentException, doing so may or may not give you any added value, this depends on what defines an ‘invalid’ argument passed through the parameter – if you can define strict rules of what can go wrong, then you may well benefit from creating more precisely named exceptions that derive fromArgumentException.Or, you could use
InvalidDataExceptionwith the same kind of informative message, if you have one:Although referring to a data stream, there might be some objections – let’s see.
If it is simply for a general ‘bad format’ exception, then you do have
FormatException– but that might be faaar too general for your circumstance (see above), though maybe a far better exception to derive from, it really does depend: