When to use try and except?

Daniel daniel.watrous at gmail.com
Fri Aug 29 13:40:22 EDT 2008


On Aug 29, 11:23 am, cnb <circularf... at yahoo.se> wrote:
> If I get zero division error it is obv a poor solution to do try and
> except since it can be solved with an if-clause.
>
> However if a program runs out of memory I should just let it crash
> right? Because if not then I'd have to write exceptions everywhere to
> prevent that right?
>
> So when would I actually use try-except?
>
> If there can be several exceptions and I just want to catch 1 or 2?
> Like
> try:
>     blahaba
> except SomeError:
>     do something

I'm not sure whay you're trying to do, but I think catching a
ZeroDivisionError exception is a good use of try-except.

I'm also not sure that I would say you just let a program crash if it
runs out of memory.  I would think that from the user perspective, you
would want to check memory conditions and come up with an exception
indicating that some memory threshold has been reached.  When that
exception is raised you should indicate that to the user and exit
gracefully.



More information about the Python-list mailing list