Proper way to handle errors in a module
MRAB
python at mrabarnett.plus.com
Wed May 11 14:08:57 EDT 2011
On 11/05/2011 18:29, Andrew Berg wrote:
> I'm a bit new to programming outside of shell scripts (and I'm no expert
> there), so I was wondering what is considered the best way to handle
> errors when writing a module. Do I just let exceptions go and raise
> custom exceptions for errors that don't trigger a standard one? Have the
> function/method return nothing or a default value and show an error
> message? I'm sure there's not a clear-cut answer, but I was just
> wondering what most developers would expect a module to do in certain
> situations.
Generally speaking, a function or method should either do what it's
expected to do, returning the expected result, or raise an exception if
it can't.
Also, it's often clearer to distinguish between a function, which
returns a result, and a procedure, which doesn't (in Python it would
return None).
For example, if you have a list, the functional form is:
sorted(my_list)
which returns a new sorted list, and the procedural form is:
my_list.sort()
which sorts in-place (modifying the list) and returns None.
More information about the Python-list
mailing list