I don't get why sys.exit(1) doesn't exit the while loop in the follow case

Arnaud Delobelle arnodel at gmail.com
Wed Oct 13 05:08:18 EDT 2010


Nobody <nobody at nowhere.com> writes:

> On Mon, 11 Oct 2010 05:42:39 -0700, Ethan Furman wrote:
>
>>>>If I'm catching exceptions in order to perform clean-up, I'll use a bare
>>>>except and re-raise the exception afterwards. In that situation, a bare
>>>>except is usually the right thing to do.
>>> 
>>> Wrong way to do it.
>> 
>> What, then, is the right way to do it?
>
> I presume that he's referring to "finally". Which is reasonable enough
> given what I wrote, but isn't always convenient.
>
> My point was that bare excepts aren't a problem if you're going to
> re-raise the exception.

If I understand correctly, there is a big difference between bare except
and finally:

>>> def f(x):
...     try:
...         if x:
...             raise ValueError("x should be falsy")
...     except:
...         print("bare except")
...         raise
...     finally:
...         print("finally")
... 
>>> f(0)
finally
>>> f(1)
bare except
finally
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in f
ValueError: x should be falsy

The finally: clause is always executed, whereas the bare except: clause
is only executed if an exception was raised in the try: clause.

-- 
Arnaud



More information about the Python-list mailing list