Search code examples
c#.netexceptionloggingthrow

What style do you use for exception messages?


In writing the code that throws the exception I asked about here, I came to the end of my message, and paused at the punctuation. I realized that nearly every exception message I've ever thrown probably has a ! somewhere.

throw new InvalidOperationException("I'm not configured correctly!");
throw new ArgumentNullException("You passed a null!");
throw new StupidUserException("You can't divide by 0!  What the hell were you THINKING???  DUMMY!!!!!");

What tone do you take when writing exception messages? When going through logs, do you find any certain style of message actually helps more than another?


Solution

  • A conversational tone in system messages makes the software look unprofessional and sloppy. Exclamation points, insults, and slang don't really have a place in polished exception messages.

    Also, I tend to use different styles in Java for runtime exceptions and checked exceptions, since runtime exceptions are addressed to the programmer that made the mistake. Since runtime exceptions might be displayed to end users, I still "keep it clean," but they can be a little more terse and cryptic. Checked exception messages should be more helpful, since it may be that the user can fix the problem if you describe it (e.g., file not found, disk full, no route to host, etc.).

    One thing that is helpful, in the absence of a specific field on the exception for the information, is the offending data:

    throw new IndexOutOfBoundsException("offset < 0: " + off);