Instance Usage of else in python Exception

  • 2021-11-10 10:03:08
  • OfStack

1. Description

When it is determined that there is no exception, there are still 1 things to do. You can use else statement.

Note: There are no exceptions in try, and the code after else will not be executed.

2. Examples


while True:
    try:
        x = int(input(' Please enter X:'))
        y = int(input(' Please enter Y:'))
        value = x / y
        print('x/y is',value)
    except Exception as e:  #  Executed when an exception occurs 
        print(' Incorrect input: ', e)
        print(' Please re-enter ')
    else:  #  Executed when no exception occurs 
        break

Instance extension:


def fetcher(obj, index):
    return obj[index]
 
x = 'spam'
 
try:
    print fetcher(x, 3)
except Exception:
    print 'hhh'
else:
    print 'has no exception'
    print fetcher(x, 2)
    print '---' * 10
 
try:
    print fetcher(x, 4)
except IndexError:
    print 'got exception'
else:
    print 'has no exception'
    print fetcher(x, 2)

Run results:


m
has no exception
a
------------------------------
got exception

Related articles: