python学习 (三十二) 异常处理

本文深入探讨了Python中异常处理的基本概念,包括try-except、else、finally和raise语句的使用,通过具体代码示例展示了如何有效管理和抛出异常。

1 异常:

def exceptionHandling():
    try:
        a = 10
        b = 0
        d = a / b
        print(d)
    except ZeroDivisionError as ex:
        print("exception 1 " + str(ex) )
    except BaseException as ex:
        print("exception 2 " + str(ex))

exceptionHandling()

2 : else(如果没有异常)

def exceptionHandling():
    try:
        a = 10
        b = "d"
        d = a / b
        print(d)
    except ZeroDivisionError as ex:
        print("exception 1 " + str(ex) )
    except BaseException as ex:
        print("base exception")
    else:                          // 如果没有上面两个异常,会走到这里
        print("OK")

exceptionHandling()

 3:Finally

def exceptionHandling():
    try:
        a = 10
        b = 5
        d = a / b
        print(d)
    except ZeroDivisionError as ex:
        print("exception 1 " + str(ex) )
    except BaseException as ex:
        print("base exception")
    else:
        print("OK")
    finally:                          // 无论有无异常,都会执行
        print("must execute")

exceptionHandling()

 4: 抛出异常

  raise  XXXX

def exceptionHandling():
    try:
        a = 10
        b = 0
        d = a / b
        print(d)
    except ZeroDivisionError as ex:
        print("exception 1 " + str(ex) )
        raise ZeroDivisionError("aaaaaaaaaaaa")                 // 可以在代码里面抛出异常
    except BaseException as ex:
        print("base exception")
    else:
        print("OK")
    finally:
        print("must execute")

exceptionHandling()

 

 

 

转载于:https://www.cnblogs.com/liufei1983/p/9865999.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值