I am trying to determine some guidelines for how to write exception messages.
For example, let us suppose a hypothetical function which must receive a constant number of bytes (as a bytes
object), and we call it with [1, 2, 3]
. The following are all potential exceptions:
1. TypeError
2. TypeError: argument must be 16 bytes
3. TypeError: argument must be 16 bytes; got 'list'
4. TypeError: argument must be 16 bytes; got 'list' [1, 2, 3]
Generally, I feel that the message should always explain the condition that wasn't met, but I'm on the fence about how much information to include about the offending object.
Are there any guidelines on this subject?
Excellent question!
When I am generally creating custom exceptions I usually go look at the Python set which is generally exhaustive.
Now as for the question as to provide how much detail, I wouldn't make them too specific because you don't know what would be triggering them or causing them.
In example:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
is descriptive enough to let me know that the +
operator isn't supported, I don't need know to know what the string contains.
So in your example first two are perfectly fine, second two are overkill IMO.
Goodluck.
I don't have much in the way of 'established idiom' links to give you, but here are my 2¢:
Your goal is for the poor sap who encouters the exception (i.e. possibly not you and/or far in the future) to have enough information to understand the problem, and hopefully fix it.
Information is communicated through exceptions in several ways:
You should also consider:
But generally, I think it's best to ask yourself: "If I got this exception in production code, what information would I want available to me?"
Personally, in the example you give, I'd go for option (4) every time. I don't think that's too much information. Your exception seems like something that should pretty much never be happening, and if it does happen, you want to know exactly what went wrong.
If you leave out information, as in (1-3), you provide an opportunity for confusion about what's really going on.
Don't give redundant information in messages - don't be verbose just for the sake of it. But communicate all relevant information for the benefit of that future maintainer who is scratching their head.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With