python基础(7)-----异常问题

---恢复内容开始---

当发生python不知所措的错误时,python会创建一个异常对象,

如果你编写处理该异常的代码,程序将会继续运行;

如果你未对异常做任何处理,程序将会停止,并显示一个traceback,其中包含异常的报告。

如果让用户看见traceback,这太low了!!


1、处理ZeroDivisionError异常

print(5/0) #0是不能作为除数的
#######################
Traceback (most recent call last):
  File "C:/software/PyCharm/alien/images/first.py", line 1, in <module>
    print(5/0)
ZeroDivisionError: division by zero

2、使用try-except代码块

当你认为可能要发生错误时,可以编写一个try-except代码块来处理可能引发的异常。

try:
    print(5/0)
    """
    如果try代码块中的代码运行起来没有问题,程序将直接跳过except代码块
    如果代码运行有问题,python将查找except代码块,并运行其中的代码
    """
except ZeroDivisionError:
    print("you can't division by zero!!!")

3、else代码块

try-except-else代码块的工作原理大致如下:

python尝试执行try代码块中的代码;只有可能引发异常的代码才会放在try语句中,一些仅在try代码块成功执行时才需要运行的代码,这些代码应放在else代码块中。

print("give me two numbers,and i will divide them!")
print("enter 'q' to quit!")
while True:
    first_number = input("first number:")
    if first_number == "q":
        break
    second_number = input("second number:")
    if second_number == "q":
        break
    try:
        anwser = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print("you can't division by zero!!!")
    else:
        print(anwser)
原文地址:https://www.cnblogs.com/jinyuanliu/p/10364997.html