1、说明

当确定没有异常后,还需要做一些事情可以使用else语句。

注意:try中没有异常,else之后的代码才会被执行。

2、实例

while True:
    try:
        x = int(input('请输入X:'))
        y = int(input('请输入Y:'))
        value = x / y
        print('x/y is',value)
    except Exception as e:  # 发生异常时执行
        print('不正确的输入:', e)
        print('请重新输入')
    else:  # 未发生异常时执行
        break

实例扩展:

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)

运行结果:

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。