To throw or to throw not?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Nov 14 05:09:13 CET 2008


On Thu, 13 Nov 2008 17:11:26 -0800, Emanuele D'Arrigo wrote:

> I'm pondering on what is a bit of a philosophical dilemma. When should I
> throw an exception and when should I not?
> 
> Suppose I have myFunc1() calling myFunc2() which in turn calls myFunc3
> ().
> Suppose myFunc3() has detected a problem. What should it do?
> 
> Throw an exception, forcing myFunc2() to handle it and/or trigger
> another exception for myFunc1() to deal with? Or should it simply return
> a meaningful error code, for myFunc2() and myFunc1() to handle as an
> option but not forcing them to do so?

In general, you should raise an exception. Then if myFunc2() can't handle 
it, it doesn't need to trigger another exception, the exception will just 
propagate up the call chain to myFunc1().

There are cases where something like a meaningful error value is 
appropriate, but the only one I can think of right now is NaN in floating 
point maths.


-- 
Steven



More information about the Python-list mailing list