python中的异常处理

什么是异常?

python使用异常对象来表示异常状态,并在遇到错误时引发异常。异常对象未被处理(或捕获)时,程序将终止并显示一条错误信息。

如何引发异常?

python为我们提供了raise语句来引发异常,并将一个类(必须是Exception的子类)或实例作为参数。注意,我们几乎所有的异常类都是从Exception派生出来的。

如何自定义异常类?

其实就是和创建普通类,但是该类必须直接或者间接继承Exception。格式如下:

class SomeException(Exception):pass

捕获异常

我们利用try...except语句来捕获异常。

def func(x,y):
    print(x/y)

try:
    a = int(input('Enter the first number:'))
    b = int(input('Enter the second number:'))
    func(a,b)
except ZeroDivisionError:
    print("the second number can't be zero")

此时,当我们输入的第二个值是非0时,程序会输出正确的运算所得值;如果输入为0时,就会打印最后一定话;而不会引起程序的崩溃。

在异常中,我们还有特别的代码块,finally代码块。该代码不管try语句中是否有错误,它都会执行。如果有错误,则执行完finally代码块后,返回错误;如果try语句块中没有错误,则按顺序执行输出。

def func(x,y):
    print(x/y)
try:
    a = 5
    b = 0
    func(a,b)
finally:
    print("finally!!!")
#finally!!!
#  File "/Users/asd/PycharmProjects/test/pythontest/test1.py", line 7, in #<module>
#    func(a,b)
#  File "/Users/asd/PycharmProjects/test/pythontest/test1.py", line 3, in func
#    print(x/y)
#ZeroDivisionError: division by zero
def func(x,y):
    print(x/y)
try:
    a = 5
    b = 0
    func(a,b)
except ZeroDivisionError:
    print("the second number can't be zero")
finally:
    print("finally!!!")

#the second number can't be zero
#finally!!!

最后再介绍一个else分句,提供没发生异常时要执行的语句。

def func(x,y):
    print(x/y)

while True:
    try:
        a = int(input('please input the first number:'))
        b = int(input('please input the second number:'))
        func(a,b)
    except (ZeroDivisionError,TypeError) as e:
        print(e)
    else:
        break
    finally:
        print("finally!!!")
#please input the first number:23
#please input the second number:0
#division by zero
#finally!!!
#please input the first number:23
#please input the second number:2
#11.5
#finally!!!

可以看到,在没有发生异常的时候,else语句才有执行跳出。

下面来总结以下异常处理语句!try/except/else/finally

try:
main-action
except Exception1:
handler1
except Exception2:
handler2...
else:
else-block
finally:
    finally-block

我们来梳理一下它的处理过程。最先开始执行的肯定是main-action模块,如果程序有问题,就会跳到exception中,看看能否捕捉到错误,如果捕捉到,就继续执行finally语句模块;如果没有,则继续执行finally语句模块后,最终程序异常终止。如果try模块没有问题,则继续执行else语句模块,然后执行finally语句模块。

最后需要注意的是,try语句必须有一个except或一个finally,else是可选的,但是如果有else,则必须至少有一个except。

warnings模块

如果我们只想发出警告,指出情况偏离了正轨,可使用模块warnings中的warn函数。那么它有什么作用?比如其他代码在使用你编写的模块,就可以使用该模块的filterwarnings来抑制你发出的警告,并指定要采取的措施,如“error”或“ignore”。

from warnings import filterwarnings
filterwarnings(“ignore”)

《python基础教程》

https://zhuanlan.zhihu.com/c_147297848

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值