catching my own exception

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Jun 18 13:45:31 EDT 2010


On Fri, 18 Jun 2010 17:08:45 +0000, nick wrote:

> I have a problem with catching my own exception. Here is the code:
> http://fly.srk.fer.hr/~nick/travapi/blame.php?repname=Travian+API&path=%
2Fvillage.py&
>
> Line 252 calls a method, which on line 207 raises a
> SomethingBeingBuiltError exception. On line 253 I catch that exception,
> but when I run that code, I get:
> 
> Traceback (most recent call last):
>   File "village.py", line 252, in <module>
>     v.upgrade_cheapest()
>   File "/media/data/home/code/travapi/village.py", line 207, in
>   upgrade_cheapest
>     raise SomethingBeingBuiltError()
> village.SomethingBeingBuiltError: 'Unable to upgrade, check if something
> is being built.'
> 
> If I change line 253 to only "except:", everything works as expected.
> How come? What am I missing? Any help would be appreciated.


I can't run your code, so I'm stuck with trying to guess how it works 
just by reading it. As far as I can tell, it should work. If it doesn't 
work, I can only imagine that you're not running the code you think you 
are running. Perhaps you're running an older version?


Other than that, I notice that your module throws away useful debugging 
information, and replaces it with bland, useless pap of no nutritional 
value:

try:
    import account, fetch, resources, const
except Exception:
    raise Exception('One or more travapi modules not available.')

Instead of a useful ImportError exception that tells the caller two 
important pieces of information (namely that it is an import error, and 
what the error actually was) you replace it with a useless, generic 
error. It might as well say "An error occurred" for all the use it is.

Errors should be *more* specific, not less. By replacing useful, specific 
exceptions with the generic Exception class, you're throwing information 
away and making your own job harder. Why would you rather see:

    Exception: One or more travapi modules not available.

instead of this?

    ImportError: No module named resources

As a general rule, anytime you find yourself writing:

    except SomeSpecificException:
        raise SomeOtherException

you should stop and think *really hard* about why you are bothering.



-- 
Steven



More information about the Python-list mailing list