python处理异常n大于2_【Python】异常处理

处理ZeroDivisionError异常

下面看一种异常,除数为0的异常,我们都知道,当除数为0的时候是不可以运算的。

print(5/0)

167dcd1427c36cd9bcd9e2bf816df02c.png

在上述Traceback中,已经指出的错误ZeroDivisionError是一个异常对象。Python无法按照你的要求做时,就会产生这种对象。

1.1使用try-except代码块

当你预先知道会发生这种错误时,可编写一个try-except代码块来处理可能发生的异常。你让python尝试运行一些代码,并告诉他如果这些代码引发了指定的异常,该怎么办

try:print(5/0)exceptZeroDivisionError:print("You can't divide by 0")

运行结果:

e2c1005bf5f7829522ff42298143bdba.png

1.2使用异常避免奔溃

发生错误时,如果程序还没有工作完成,妥善的处理错误尤其重要,这种情况经常会出现在要求用户提供的主程序中,如果程序能够妥善的处理无效请求,就能再提示用户提供有效输入,而不至于奔溃

下面是一个简易计算机

print("Give me two number,I will divide them!")print("Enter the 'q' to quit!")whileTrue:

first_number= input("\nEnter the first number:")if first_number == 'q':breaksecond_number= input("\nEnter the second number:")if int(second_number) ==0:

second_number= input("\nYou can't divide by 0,please re-Enter the second number:")if second_number == 'q':breakanswer= int(first_number)/int(second_number)print(answer)

运行结果

c3ccc4063e1db023f13b290c9224faa6.png

当输入的分母为0时也做了相应处理,这种是使用if语句强行判断处理分母为0的情况,那么使用异常处理该如何处置呢?

print("Give me two number,I will divide them!")print("Enter the 'q' to quit!")whileTrue:

first_number= input("\nEnter the first number:")if first_number == 'q':breaksecond_number= input("\nEnter the second number:")if second_number == 'q':break

try:

answer= int(first_number)/int(second_number)exceptZeroDivisionError:

second_number= input("\nYou can't divide by 0,please re-Enter the second number:")

answer= int(first_number) /int(second_number)print(answer)else:print(answer)

当除法产生异常的时候,就提示重新输入不为0的除数。

处理FileNotFoundError异常

file_path = "txt\MyFavoriteFruit.txt"

try:

with open(file_path) as file_object:

Contents=file_object.readlines()for line inContents:print(line.strip())exceptFileNotFoundError:

msg= "Sorry,the file" + file_path + "does not exist."

print(msg)

当文件存在时候,运行结果:

5434f3b645b29caa433f9f0ce9d1d1ab.png

删除文件后的运行结果:

489bc194baffc5473b7a7611c369e08b.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值