Python基础---异常处理

        程序在运行时会碰到一些错误,如除数为0,数组下标越界等等,这些错误不加以处理,会导致程序产生报错,后面的代码都无法运行。

常见的异常类型
异常类型 含义 实例
AssertionError 当 assert 关键字后的条件为假时,程序运行会停止并抛出 AssertionError 异常 >>> demo_list = ['C语言中文网']
>>> assert len(demo_list) > 0
>>> demo_list.pop()
'C语言中文网'
>>> assert len(demo_list) > 0
Traceback (most recent call last):
  File "", line 1, in
    assert len(demo_list) > 0
AssertionError
AttributeError 当试图访问的对象属性不存在时抛出的异常 >>> demo_list = ['C语言中文网']
>>> demo_list.len
Traceback (most recent call last):
  File "", line 1, in
    demo_list.len
AttributeError: 'list' object has no attribute 'len'
IndexError 索引超出序列范围会引发此异常 >>> demo_list = ['语文']
>>> demo_list[3]
Traceback (most recent call last):
  File "", line 1, in
    demo_list[3]
IndexError: list index out of range
KeyError 字典中查找一个不存在的关键字时引发此异常 >>> demo_dict={'Python教程网':"c.biancheng.net"}
>>> demo_dict["Python网"]
Traceback (most recent call last):
  File "", line 1, in
    demo_dict["Python网"]
KeyError: 'Python网'
NameError 尝试访问一个未声明的变量时,引发此异常 >>> Python教程
Traceback (most recent call last):
  File "", line 1, in
    Python教程
NameError: name 'Python教程' is not defined
TypeError 不同类型数据之间的无效操作 >>> 1+'你好'
Traceback (most recent call last):
  File "", line 1, in
    1+'你好'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
ZeroDivisionError 除法运算中除数为 0 引发此异常 >>> a = 1/0
Traceback (most recent call last):
  File "", line 1, in
    a = 1/0
ZeroDivisionError: division by zero

        当一个程序发生异常时,代表该程序在执行时出现了非正常的情况,无法再执行下去。默认情况下,程序是要终止的。如果要避免程序退出,可以使用捕获异常的方式获取这个异常的名称,再通过其他的逻辑代码让程序继续运行,这种根据异常做出的逻辑处理叫作异常处理。

捕捉异常
#try...except...语句捕捉异常时,程序从上往下运行,如果第一个except捕捉到异常,那后面的excep语句就不会运行
try:
    #这里放上可能会产生报错的代码
    user_weight = float(input("请输入您的体重(单位:kg):"))
    user_height = float(input("请输入您的身高(单位:m):"))
    user_BMI = user_weight / user_height ** 2
except ValueError:  #except后面跟上想要捕捉的错误名字以及冒号
    #错误发生后想要执行的操作
    print("输入不为合理的数字,请重新运行程序,并输入正确的数字。")
except ZeroDivisionError:   #产生除零错误时会运行
    print("身高不能为零,请重新运行程序,并输入正确的数字。")
except: #这个语句会捕捉所有的错误类型 产生其他错误时会运行
#这种用法要谨慎,因为它会隐藏所有未预期的错误(包括程序逻辑错误)
    print("发生了未知错误,请重新运行程序。")
else:
    print(f"您的BMI值为:{user_BMI}") #没有错误时会运行
finally:
    #无论错误发生与否最终都会被执行
    print("程序运行结束。")

你可能感兴趣的:(Python基础,python)