try-except-else-finally语句

try-except-else代码块的工作原理大致如下:Python尝试执行try代码块中的代码,只有可能引发异常的代码才放到try语句中,有时候,有时候,有一些try代码块成功执行时才需要运行的代码,这些代码应该放到else语句中。except代码块告诉Python,如果它尝试运行try代码块中代码引发出了指定的异常时,该怎么办。except可以有多个。finally是不管有没有异常都会执行的代码。
示例:

"""
通过将可能引发错误的代码放在try-except代码块中,可提高这个程序抵御错误的能力。错误是执行除法运算的代码行导致的,
因此我们需要将它放到try-except代码块中。这个示例还包含一个else代码块;依赖于try代码块成功执行的代码都应放到
else代码块中: 
"""

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 = float(first_number) / float(second_number)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer)
    finally:
        print('验证结束')

猜你喜欢

转载自blog.csdn.net/hs_blog/article/details/80873938
今日推荐