baffling error-handling problem

Scott David Daniels Scott.Daniels at Acm.Org
Thu Jul 28 12:11:02 EDT 2005


Chris Fonnesbeck wrote:
> I thought I knew how to do error handling in python, but apparently I
> dont. I have a bunch of code to calculate statistical likelihoods, and
> use error handling to catch invalid parameters. For example, for the
> bernoulli distribution, I have:
> 
>     def bernoulli_like(self, x, p, name='bernoulli'):
>         ... if sum(p>=1 or p<=0): raise LikelihoodError ...
> 
> where LikelihoodError is simply a subclass of ValueError that I created:
> 
>     class LikelihoodError(ValueError):
>         "Log-likelihood is invalid or negative infinite"
> 
> I catch these errors with the following:
> 
>         try: like = self.calculate_likelihood()
>         except LikelihoodError:
>             return 0
>
 > ... [when using] ...
>      like=self.bernoulli_like(x,p)
> 
> I get the following when an invalid parameter is passed:
> 
> Traceback (most recent call last):
>   File "...\model_000.py", line 381, in ?
>     model.sample(iterations=iter, burn=burn,plot=False)
>   File "...\PyMC\MCMC.py", line 1691, in sample
>     self._like = self.calculate_likelihood()
>   File "...\model_000.py", line 194, in calculate_likelihood
>     like+=self.bernoulli_like(x,p)
>   File "...\MCMC.py", line 868, in bernoulli_like
>     if sum(p>=1 or p<=0): raise LikelihoodError
> LikelihoodError
> 
> I have no idea how this can happen, given how I have coded this.

Might you be referring to a different LikelihoodError in the
   try: ... except ... part of your code than in the ... raise ... part?
Similarly defined classes are not the same class.  If you didn't
get LikelihoodError in mode4l_000.py with the moral equivalent of
      from MCMC import LikelihoodError
then this is what is going wrong.
By the way, if it were I, I'd:    raise LikelihoodError(p)  just so I
could discover a bit of what went wrong.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list