python入门-异常

1 报错的例子

print(5/0)

2跳过报错的例子

try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero")
print("Give me two numbers , and I'll divide them.")
print("Eneter '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:
        answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer)

3 文件不存在的异常

filename = '55.txt'
try:
    with open(filename) as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
    msg = "sorry,the file " + filename + "does not exist."
    print(msg)
else:
    words = contents.split()
    num_words = len(words)
    print("The file " + filename + "has about" + str(num_words) + "words")

4 跳过的异常的函数

def count_words(filename):
    """计算一个文件包含多少个单词"""
    try:
        with open(filename) as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:
        pass
    else:
        words = contents.split()
        num_words = len(words)
        print("The file " + filename + "has about" + str(num_words) + "words")
原文地址:https://www.cnblogs.com/baker95935/p/9437884.html