处理ZeroDivisionError异常
下面看一种异常,除数为0的异常,我们都知道,当除数为0的时候是不可以运算的。
print(5/0)
在上述Traceback中,已经指出的错误ZeroDivisionError是一个异常对象。Python无法按照你的要求做时,就会产生这种对象。
1.1使用try-except代码块
当你预先知道会发生这种错误时,可编写一个try-except代码块来处理可能发生的异常。你让python尝试运行一些代码,并告诉他如果这些代码引发了指定的异常,该怎么办
try:print(5/0)exceptZeroDivisionError:print("You can't divide by 0")
运行结果:
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)
运行结果
当输入的分母为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)
当文件存在时候,运行结果:
删除文件后的运行结果: