top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the optional statement used in a try ... except statement in Python?

+3 votes
75 views
What is the optional statement used in a try ... except statement in Python?
posted Jan 31, 2015 by Amit Kumar Pandey

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

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:

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print 'cannot open', arg
    else:
        print arg, 'has', len(f.readlines()), 'lines'
        f.close()
answer Jul 11, 2016 by anonymous
...