Loading

Python异常处理

异常

程序在运行过程中,难免会遇到问题和错误。有一些错误是不可预料的,这些错误可能会导致程序在运行过程中出现异常中断和退出,对于这样的错误我们需要进行处理。

# ZeroDivisionError: division by zero
print(1/0)

# TypeError
print(1 + '1')

语法:

try:
    可能发生错误的代码
except:
    出现异常时要执行的代码

示例:

尝试打开不存在的文件,使用try...catch...处理

try:
    f = open('test.txt', 't')
except:
    f = open('test.txt', 'w')

捕获指定的异常类型

语法:

try:
    可能发生错误的代码
except 异常类型:
    捕获到指定异常类型时执行的代码

示例:

try:
    print(1/0)
except ZeroDivisionError:
    print('出现了错误')

注:如果发生的异常类型和要捕获的异常类型不一致,则无法捕获异常。

# ZeroDivisionError: division by zero
try:
    print(1/0)
except NameError:
    print('出现了错误')

捕获多个异常:

当需要捕获多个异常时,可以把要捕获的异常类型的名字,放到except后面,使用元组的方式进行书写。

try:
    print(1/0)
except (NameError, ZeroDivisionError):
    print('出现了错误')

捕获异常描述信息:

try:
    print(1/0)
except (NameError, ZeroDivisionError) as result:
    print(result)

捕获所有异常:

Exception是所有异常类的父类。

try:
    print(1/0)
except Exception as result:
    print(result)

异常中的else:

else表示当没有异常的时候执行的代码。

try:
    print(1/1)
except Exception as result:
    print(result)
else:
    print('当没有异常的时候执行的代码...')

异常中的finally:

finally表示的是无论是否异常都会执行的代码。

try:
    f = open('test.txt', 't')

except Exception as e:
    f = open('test.txt', 'w')
finally:
    print('最终执行的代码')
    f.close()

自定义异常

自定义异常应该继承Exception类,在Python中使用关键字raise,可以主动抛出指定的异常。

# 自定义异常类,需要继承Exception,str方法设置异常描述信息
class MyExcept(Exception):
    def __init__(self, length, min_len):
        self.length = length
        self.min_len = min_len

    # 设置异常描述信息
    def __str__(self):
        return f'你输入的密码长度是{self.length},不能小于{self.min_len}'

def main():
    try:
        password = input('请输入密码:')
        if len(password) < 6:
            # 抛出异常类创建的对象
            raise MyExcept(len(password), 6)
    # 捕获该异常
    except Exception as res:
        print(res)
    else:
        print('你输入的密码没有异常')

main()
posted @ 2021-07-05 09:39  charlatte  阅读(45)  评论(0编辑  收藏  举报