[Tutor] Two sys.exit questions

Jason Massey jason.massey at gmail.com
Wed Feb 28 19:07:06 CET 2007


When you call sys.exit() you're raising a SystemExit exception.

>>> help(sys.exit)
Help on built-in function exit in module sys:

exit(...)
    exit([status])

    Exit the interpreter by raising SystemExit(status).
    If the status is omitted or None, it defaults to zero (i.e., success).
    If the status is numeric, it will be used as the system exit status.
    If it is another kind of object, it will be printed and the system
    exit status will be one (i.e., failure).

So that explains why you're falling through to except clause.
You can see the same type of behavior if you manually raise an exception
(ValueError for example) within a try clause

In your example concerning the reading and writing to files, as far as a
close() statement goes you would get this error:
>>> try:
...     i_file = open('doesnt_exit.tmp','r')
... except IOError:
...     i_file.close()
...
Traceback (most recent call last):
  File "<interactive input>", line 4, in ?
NameError: name 'i_file' is not defined
>>>

Since i_file never got defined because the open wasn't successful.

BTW don't use file as a variable since it will mask python's built-in file
object

On 2/28/07, Cecilia Alm <flickita at gmail.com> wrote:
>
> I have two quick questions:
>
> 1) Why does sys.exit() not work in a try clause (but it does in the except
> clause)?
>
> >>> try:
> ...    print 1
> ...    sys.exit(0)
> ... except:
> ...    print 2
> ...    sys.exit(0)
> ...
> 1
> 2
> # python exited
>
> 2) If opening a file fails in the below 2 cases, sys.exit(message) prints
> a message in the except clause before program termination.
>     Some use file.close() in the except clause (or in a finally clause).
> It seems superflous in the below case of read and write. (?)
>
>         try:
>             file = open('myinfile.txt', 'r')
>         except IOError:
>             sys.exit('Couldn't open myinfile.txt')
>
>         try:
>             file = open('myoutfile.txt', 'w')
>         except IOError:
>             sys.exit('Couldn't open myoutfile.txt')
>
>
>
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070228/61c0390d/attachment.htm 


More information about the Tutor mailing list