1.异常
异常是使用try-except代码块处理的。try-except代码块让Python执行指定的操作,同时告诉Python发生异常时怎么办。
使用了try-except代码块时,即便出现异常,程序也将继续运行:显示你编写的友好错误消息,而不是令用户迷惑的traceback.。
print(5/0)
Traceback (most recent call last): File "exception_division", line 1, in <module> print(5/0) ZeroDivisionError: division by zero
程序奔溃可不好,让用户看到traceback也不是好主意,恶意用户将知道你程序的文件名,还将看到部分不能正确运行的代码。
print("Give me two numbers,and I‘ll divide them.") print("Enter ‘q‘ to quit.") while True: first_number=input("\nFirst number: ") if first_number == ‘q‘: break second_number=input("Second number: ") if second_number == ‘q‘: break try: answer=int(first_number)/int(second_number) except ZeroDivisionError: print("You can‘t divide by 0!") else: print(answer)
Give me two numbers,and I‘ll divide them. Enter ‘q‘ to quit. First number: 5 Second number: 0 You can‘t divide by 0! First number: 5 Second number: 2 2.5 First number: q
这样,用户看到的是一条友好的错误消息,而不是traceback。
原文:https://www.cnblogs.com/exciting/p/8996764.html