#881 – When to Throw Exceptions
July 5, 2013 Leave a comment
Your code should throw an exception when
- Something has gone wrong and your code cannot execute normally
- You catch an exception and want to add some additional information
- You catch an exception and your application cannot gracefully recover from the problem
Some examples of when you might throw an exception:
- Parameter value that is out of range passed to a function
- Parameter values that are inconsistent passed to a function
- Invalid values passed to function (e.g. username with wrong password)
- Function called while application is in the wrong state
Do not throw exceptions
- As part of normal operation, to control program flow
- To return data back to code that called a function
- Just to indicate which function was executing when an exception was caught