When should a function raise an exception instead of returning an error value?
Quick answer
Return a value when an outcome is an ordinary possibility that callers are expected to handle as part of the task, such as finding no match. Consider raising an exception when the function cannot complete its promised operation and the caller should handle or propagate that failure separately. Make each outcome clear, avoid confusing errors with valid results, and follow the project’s conventions.
The question, the details, the next step.
A practical checklist
List successful results and expected alternatives, such as no match.
Specify what a normal caller should do for each outcome.
Choose an explicit return representation for routine alternatives callers need to distinguish.
Consider an exception when the promised operation cannot be completed and the caller should handle or propagate the failure.
Check that an error marker cannot be mistaken for a valid result, and document the contract.
A few more useful answers
Is returning `None` always a good way to indicate failure?
No. It can work when absence is a clear, expected outcome and None cannot be confused with a valid result. Otherwise, choose a clearer representation or an exception, and document the contract.
Should I catch every exception inside the function that raises it?
Not necessarily. Handle an exception where there is enough context to respond usefully. If the function cannot recover or add useful context, catching it may obscure the failure.
Does the C++/WinRT guidance decide what Python code should do?
No. It is specific to C++/WinRT. The Python source cited here describes how exceptions exit a function and can be caught farther up the call stack; it does not settle which signaling style to choose.
Sources
References used for this guide.
- [S1] Error handling with C++/WinRT — guidance on expected failures learn.microsoft.com · Checked
- [S2] The Working Programmer — Python: Flow Control learn.microsoft.com · Checked
