What exception to throw when parsing an array of bytes? (WITH#)

I am parsing an array of bytes, which is actually a fixed length of the record that is sent on the message bus. If the data is invalid (distorted or does not meet the specification for the record), then I want to throw an exception. Something like that:

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 that I can use in these circumstances, or should I just create my own specific exception?

+4
source share
4 answers

You can simply use ArgumentException :

 throw new ArgumentException("payload", "'payload' should be..."); 

As mentioned below, x0r, MSDN recommends only getting an ArgumentException , it may or may not give you added value, it depends on what defines the "invalid" argument passed through the parameter - if you can define strict rules for what can go wrong, then you can benefit from throwing more precisely named exceptions derived from ArgumentException .

Or you can use InvalidDataException with the same informative message if you have one:

An exception that occurs when the data stream is in an invalid format.

Despite accessing the data stream, some objections may arise - let's see.

If this is just a general โ€œbad formatโ€ exception, then you have a FormatException - but it may be too general for your circumstance (see above), although perhaps this is a much better exception that it really depends on:

The exception that is thrown when the argument format does not match the parameter specifications of the called method.

+3
source

You can throw an ArgumentException with a custom InnerException.

+2
source

If the data reliability criterion is application-specific and does not correspond to the general case (for example, an index out of range, etc.), I think it is better to use your own exception. For the standard case, an existing exception is used, for example, NullPointerException if the payload == null.

+2
source

System.ArgumentOutOfRangeException :

An ArgumentOutOfRangeException is thrown when the method is called and if at least one of the arguments passed to the method is non-zero and does not contain a valid value.

 throw new ArgumentOutOfRangeException("payload","description of the specific problem"); 
0
source

All Articles