开发者

What exception to throw when parsing a byte array? (C#)

I'm parsing a byte array, which is in effect a fix 开发者_JS百科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:

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

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 from ArgumentException.

Or, you could use InvalidDataException with the same kind of informative message, if you have one:

The exception that is thrown when a data stream is in an invalid format.

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:

The exception that is thrown when the format of an argument does not meet the parameter specifications of the invoked method.


You may throw an ArgumentException with a custom InnerException.


If data validity criterion is application-specific and doesn't match any general case (like index out of range etc.), I think it is better to use your own exception. For standard case use existing exception, for example, NullPointerException if payload == null.


System.ArgumentOutOfRangeException:

ArgumentOutOfRangeException is thrown when a method is invoked and at least one of the arguments passed to the method is not null and does not contain a valid value.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜