首页 > 技术文章 > 第九章第2讲:异常

ling07 2019-07-25 15:50 原文

1. 案例

try:
    x = int(input("Enter the first number:"))
    y = int(input("Enter the second number:"))
    print(x/y)
except ZeroDivisionError:
    print("The second number can't be zero.")

2. try中的可疑代码块,异常情况可能不仅仅是一类,可能是多类,该如何处理?

  考虑使用try与多个except结合

try:
    x = int(input("Enter the first number:"))
    y = int(input("Enter the second number:"))
    print(x/y)
except ZeroDivisionError:
    print("The second number can't be zero.")
except ValueError:
    print('your input is not a number. ')

3. 可以把多个异常类放在1个except中,一个except捕捉多个异常

 

try:
    x = int(input("Enter the first number:"))
    y = int(input("Enter the second number:"))
    print(x/y)
except (ZeroDivisionError,ValueError):
    print("Your input can't be used.")

 

 4. 全捕捉

  注意:不推荐,因为给出异常提示信息不够详细

try:
    x = int(input("Enter the first number:"))
    y = int(input("Enter the second number:"))
    print(x/y)
except:
    print("It's wrong.")

 5. 在实际情况中,有时希望看到异常本身的信息

  except() as e

try:
    x = int(input("Enter the first number:"))
    y = int(input("Enter the second number:"))
    print(x/y)
except(ZeroDivisionError,ValueError) as e:
    print("It's wrong.")
    print(e)

 

 6. try--except--else

     注意:else放在except之后

    else是在try内可疑代码块,未发生异常时执行  

try:
    x = int(input("Enter the first number:"))
    y = int(input("Enter the second number:"))
    print(x/y)
# 捕捉被除数为0的情况
except ZeroDivisionError:
    print("被除数为0")
# 捕捉多个异常,类型错误、值错误
except (ValueError,TypeError) as e:
    print("输入的不是数字")
# else在try内容中的代码,无异常时,执行
else:
    print("结果正确运行")

   try--except--else案例的升华

while True:
    try:
        x = int(input("Enter the first number:"))
        y = int(input("Enter the second number:"))
        print(x/y)
    except Exception as e:
        print("The invalid info is :",e)
    else:
        print("计算结束")
        break

 

推荐阅读