Day4-----异常

异常组成:异常类型:异常描述信息
ZeroDivisionError: division by zero
ValueError: invalid literal for int() with base 10: 'a'

捕获异常:在程序运行过程中遇到错误,不让程序终止,继续运行,并给使用者一个异常信息,记录这个错误


捕获单个异常
try:
    可能发生异常的代码
except 异常类型:
    发生异常执行的代码

try:
    num=input('请输入一个数值')
    num=10/int(num)
    print(num)

# ZeroDivisionError: division by zero
# ValueError: invalid literal for int() with base 10: 'a'
except ZeroDivisionError:
    print('除数不能为0')

捕获多个异常
try:
    可能发生异常的代码
except (异常类型1,异常类型2,...):
    发生异常执行的代码

try:
    可能发生异常的代码
except 异常类型1:
    发生异常执行的代码
except 异常类型2:
    发生异常执行的代码
    .......

try:
    num=input('请输入一个数值')
    num=10/int(num)
    print(num)

# ZeroDivisionError: division by zero
# ValueError: invalid literal for int() with base 10: 'a'
except ZeroDivisionError:
    print('除数不能为0')
except ValueError:
    print('输入错误,请输入数字')


打印异常信息  as关键字

try:
    可能发生异常的代码
except 异常类型1 as 变量名:
    print(异常变量名)
    发生异常执行的代码
except 异常类型2 as 变量名:
    print(异常变量名)
    发生异常执行的代码
    .......


捕获所有异常  缺点:不能获取异常信息
try:
    可能发生异常的代码
except Exception:
    发生异常执行的代码

Exception 常见异常类的父类
ZeroDivisionError-->ArithmeticError-->Exception-->BaseException-->object
ValueError-->Exception-->BaseException-->object

异常的完整结构
try:
    可能发生异常的代码
except Exception:
    发生异常执行的代码
else:
    没有发生异常的代码
finally:
    不管有没有异常都会执行

异常的传递  python异常处理的底层机制  原理
当一行代码发送异常,会向外层将异常传递,来报错或者异常捕获
1. try嵌套中
    如果try嵌套,那么如果里面的try没有捕获到这个异常,那么外面的try会接收到这个异常,
然后进行处理,如果外边的try依然没有捕获到,那么再进行传递。。。
import time
try:
    f = open('test.txt')
    try:
        while True:
            content = f.readline()
            if len(content) == 0:
                break
            time.sleep(2)
            print(content)
    finally:
        f.close()
        print('关闭文件')
except:
    print("没有这个文件")
2. 函数嵌套调用中
    如果一个异常是在一个函数中产生的,例如函数A-->函数B-->函数C,而异常是在函数C中产生的,
那么如果函数C中没有对这个异常进行处理,那么这个异常会传递到函数B中,如果函数B有异常处理那么
就会按照函数B的处理方式进行执行;如果函数B也没有异常处理,那么这个异常会继续传递,以此类推。。
如果所有的函数都没有处理,那么此时就会进行异常的默认处理,即通常见到的那样
def test1():
        print("----test1-1----")
        print(num)
        print("----test1-2----")
    def test2():
        print("----test2-1----")
        test1()
        print("----test2-2----")
    def test3():
        try:
            print("----test3-1----")
            test1()
            print("----test3-2----")
        except Exception as result:
            print("捕获到了异常,信息是:%s"%result)
        print("----test3-2----")
    test3()
    print("------华丽的分割线-----")
    test2()

抛出自定义异常
    raise语句引发一个异常
    异常/错误对象须有个名字
    应是Error或Exception类的子类
1、自定义异常类,继承Exception或BaseException
2、选择书写,定义__init__,__str__方法
3、合适时机抛出异常对象


'''
class PasswardLengthError(Exception):
    pass
def get_passward():
    passward=input('请输入密码')
    if len(passward)>=6:
        print('密码长度合格')
    else:
        raise PasswardLengthError('密码长度不够六位')
try:
    get_passward()
except PasswardLengthError:
    print('密码长度不够六位')

猜你喜欢

转载自blog.csdn.net/m0_46493223/article/details/126090975
今日推荐