华域联盟 Python python异常中else的实例用法

python异常中else的实例用法

文章目录[隐藏]

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

到此这篇关于python异常中else的实例用法的文章就介绍到这了,更多相关python异常中else的使用内容请搜索华域联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持华域联盟!

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » python异常中else的实例用法

转载请保留出处和原文链接:https://www.cnhackhy.com/28207.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部