If you want to play around with this stuff, you can first import sys, and then insert this line in the except clause: print repr(sys.exc_info()) (or some other way of getting the details out of the returned tuple.)
That will tell you exactly what brought you to the except clause. On Feb 28, 2007, at 12:07 PM, Jason Massey wrote: > 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 <[EMAIL PROTECTED]> 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@python.org > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- -dave---------------------------------------------------------------- Science arose from poetry... when times change the two can meet again on a higher level as friends. -Göthe _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor