pyhotn笔记7-异常处理

什么是异常

  • 代码没有语法问题,可以运行。但会运行时出错,例如除零错误,下标越界等问题。这种在运行期间检测到的错误被称为异常。
  • 出现了异常必须处理,否则程序会终止执行,用户体验很差。
  • python支持程序员自己处理检测到的异常。
  • 可以使用try-except语句进行异常的检测和处理。

python中常见的异常类型

在这里插入图片描述

"""
NameError
"""
# 函数名拼写错误
# prlnt('hello world')# NameError: name 'prlnt' is not defined. Did you mean: 'print'?
# 变量名拼写错误
a = '111'
# print(aa) #NameError: name 'aa' is not defined. Did you mean: 'a'?
# 使用一个不存在的变量
# print(b)  # NameError: name 'b' is not defined

'''
SyntaxError
'''
# if 'he' == 'hi'
#     print('hello')#SyntaxError: expected ':'

'''
IndentationError
'''
# if 'he' == 'hi':
# print('hello')  # IndentationError: expected an indented block after 'if' statement on line 11

'''
TypeError
'''
# print(3+'2')#TypeError: unsupported operand type(s) for +: 'int' and 'str'
tp = (1,3,5)
# tp[2]=4
# print(tp) #TypeError: 'tuple' object does not support item assignment

'''
AttributeError
'''
# tp.append(2)
# print(tp)#AttributeError: 'tuple' object has no attribute 'append'

'''
KeyError
'''
d = {1:2,3:4}
# print(d[2])#KeyError: 2

'''
IndexError
'''
print(tp[4])#IndexError: tuple index out of range

try-except语句

在这里插入图片描述

  1. 首先执行try中【代码块A】,如果出现异常,立即终止代码执行,转而到except块中进行异常处理。
  2. 异常处理except模块可以多个,从上往下匹配,如果能够匹配成功,立即执行相应的异常处理代码块,执行完毕后,不再往下匹配转到3执行。
  3. 执行异常处理完毕后,如果有finally自居则执行finally字句,没有执行下面。
  4. 如果匹配不到异常,有finally执行finally语句,然后抛出异常,终止程序执行。
  5. 如果没有异常,如果有else语句,则执行else语句,执行玩else后,有finally字句则执行,没有则执行后续语句。
try:
    n = int(input('请输入数字:'))
    n = 5 / n
    print(n)
except ZeroDivisionError as e:
    print('除数不能为0')
    print('原始报错信息', e)
except:
    print('请输入一个数字')
else:
    print('运行没有被except语句捕获,执行else模块')
finally:
    print('无论如何都要执行finally模块')

raise关键字

try:
    pwd = input('请输入密码:')
    if len(pwd) < 8:
        raise Exception("密码长度不够")
except Exception as e:
    print(e)
')
    if len(pwd) < 8:
        raise Exception("密码长度不够")
except Exception as e:
    print(e)
  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值