Try Except Else


/ Published in: Python
Save to your folder(s)

The try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:


Copy this code and paste it in your HTML
  1. for arg in sys.argv[1:]:
  2. try:
  3. f = open(arg, 'r')
  4. except IOError:
  5. print 'cannot open', arg
  6. else:
  7. print arg, 'has', len(f.readlines()), 'lines'
  8. f.close()

URL: https://docs.python.org/2/tutorial/errors.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.