[Tutor] How to handle exceptions raised inside a function?

Jerry Hill malaclypse2 at gmail.com
Tue Nov 30 21:18:46 CET 2010


On Tue, Nov 30, 2010 at 3:00 PM, Richard D. Moores <rdmoores at gmail.com> wrote:
> Both Hlist and Glist must contain only positive numbers, so I really
> need to test for this inside each function. But is there a good way to
> do this? What should the functions return should a non-positive number
> be detected? Is there a conventional Pythonic way to do this?

If the value passed to the function is illegal, you should raise a
ValueError exception.  Something like this in your harmonic_mean
function, maybe:

if not all(x > 0 for x in Hlist):
	raise ValueError("All items in Hlist must be positive numbers.")

-- 
Jerry


More information about the Tutor mailing list