【Python进阶(一)】——异常与错误

🍉CSDN小墨&晓末:https://blog.csdn.net/jd1813346972

   个人介绍: 研一|统计学|干货分享
         擅长Python、Matlab、R等主流编程软件
         累计十余项国家级比赛奖项,参与研究经费10w、40w级横向

【Python进阶(一)】——异常与错误,建议收藏!


该篇文章主要演示Python中的异常与错误,包括try/except/finally的使用;异常信息显示模式;断言等内容。

1 try/except/finally

  运行程序:

try: #可能发生异常的语句
    f=open('myfile.txt','w')
    while True:
        s=input("请输入Q")
        if s.upper()=='Q':break
        f.write(s+'\n')
except KeyboardInterrupt: #发生此异常时,要执行的语句;except:发生其他异常时要执行的语句;else:无异常时,要执行的语句
    print("程序中断")
finally:
    f.close()#不管是否发生异常,都要执行的语句

  运行结果:

请输入Qq

2 异常信息的显示模式

2.1 异常信息显示模式1:Plain

  运行程序:

%xmode Plain  #异常信息显示模式1:Plain
x=1
x1

  运行结果:

Exception reporting mode: Plain
Traceback (most recent call last):

  File "<ipython-input-37-d5101d382d83>", line 3, in <module>
    x1

NameError: name 'x1' is not defined

2.2 异常信息显示模式1:Plai2

  运行程序:

%xmode Verbose #异常信息显示模式2:Verbose
x=1
x1

  运行结果:

Traceback (most recent call last):

  File "<ipython-input-38-443ceef4ba36>", line 3, in <module>
    x1

NameError: name 'x1' is not defined

2.3 异常信息显示模式3:Context(默认值)

  运行程序:

%xmode Context  #异常信息显示模式3:Context(默认值)
x=1
x1

  运行结果:

Traceback (most recent call last):

  File "<ipython-input-39-d2b0226b5ef6>", line 3, in <module>
    x1

NameError: name 'x1' is not defined

3 断言

  运行程序:

##断言主要用于“设置检查点”
a=1
b=2
assert b!=0 , "分母不能等于0"  #assert后未检查条件,当此条件为假时,抛出断言,条件为真,则不能抛出AssertionError

a=1
b=0
assert b!=0 , "分母不能等于0"  #条件为假,抛出AssertionError

  运行结果:

Traceback (most recent call last):

  File "<ipython-input-44-b71c74981dc7>", line 3, in <module>
    assert b!=0 , "分母不能等于0"

AssertionError: 分母不能等于0
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值