美文网首页
2019-06-20--Python-try语句--finall

2019-06-20--Python-try语句--finall

作者: heiqimingren | 来源:发表于2019-06-20 23:28 被阅读0次

网址:https://book.apeland.cn/details/321/

try:
    """your code"""
except Exception: #这是万能语句。
    """上面的程序执行出错后就指行这里的代码,没出错就不执行"""

需求:将用户输入的两个数字相加

while True:
    num1 = input('num1:')
    num2 = input('num2:')
    try:
        num1 = int(num1)
        num2 = int(num2)
        result = num1 + num2
    except Exception as e:
        print('出现异常,信息如下:')
        print(e)
image.png

写程序时需要考虑到try代码块中可能出现的任意异常,可以这样写:

s1 = 'hello'
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)

如果上面3个异常依然没有匹配到对应的错误 怎么办? 可以在程序最后加上Exception这个万能异常。

s1 = 'hello'
try:
    #int(s1)
    print(d)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)
except Exception as e:
    print("最后的万能异常",e)
输出:
最后的万能异常 name 'd' is not defined

其它异常结构

try:
    # 主代码块
    pass
except KeyError,e:
    # 异常时,执行该块
    pass
else:
    # 主代码块执行完,若未触发任何异常,执行该块
    pass
finally:
    # 无论监测的代码是否发生异常,都执行该处代码
    pass

主动触发异常

try:
    raise Exception('错误了。。。')
except Exception as e:
    print(e)

自定义异常
以后你写的软件若想自定义一个异常的话,就可以用下面方法

class MyException(BaseException): # BaseException是所有异常的基类
    def __init__(self,msg):
        self.message = msg
    def __str__(self):
        return self.message
try:
    raise MyException("我的错误")
except MyException as e:
    print(e)

相关文章

网友评论

      本文标题:2019-06-20--Python-try语句--finall

      本文链接:https://www.haomeiwen.com/subject/ygwsqctx.html