Skip to content

Instantly share code, notes, and snippets.

@davkean
Created August 22, 2014 06:06
Show Gist options
  • Save davkean/13c551718b0b6d6850de to your computer and use it in GitHub Desktop.
Save davkean/13c551718b0b6d6850de to your computer and use it in GitHub Desktop.
"Contract breaking" exceptions
You do not want to derive from InvalidOperationException. It and ArgumentException (and derivatives) are considered “contract breaking” exceptions.
Contract breaking exceptions should only be thrown to indicate that the caller has a bug. I pretend that every time I go to throw these exceptions that the process will be torn down immediately. If I’m okay with that, then I throw it, if not, then I should be throwing a different exception type.
Examples of contract breaks:
- You passed me index that was greater or equal to the number elements in the collection (returned by Count property)
- You passed me null, when I need a non-null value
- You passed me an empty string, when I need a non-empty string
- You called Start, but you’ve not set the ExecutablePath property.
- You called Deactivate, but the IsActive property is false
All of these things have something in common; they can all be checked up front by the caller. If the caller cannot check the condition on which you throw up-front (or doing so would be prohibitively expensive, or doing as much work as the method itself) then do not throw InvalidOperationException or ArgumentException (or one of their derived exceptions).
These are examples of bad throws of these exceptions (some of which currently exist the framework):
- The path you passed is incorrectly formatted (IO incorrectly throws ArgumentException, should have been FormatException - how is caller supposed to validate something as complex as a path?).
- The string you passed cannot be parsed as an integer (FormatException).
- The server you specified could not be found (Create your own exception type derived from Exception)
- The server returned an error code (Create your own exception type derived from Exception)
- The file could not be found (FileNotFoundException)
DataServiceException below is an example of the someone deriving from the incorrect exception. They should have directly derived from Exception.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment