【Python】程序在运行失败时,一声不吭继续运行pass

在前面程序出现异常时,我们都会给一个提示,告诉用户,程序为什么会异常,但是现在我们想在程序出现异常时,不做处理,让程序默默的往下执行,不要做声。

那么我们就引入了pass语句

def count_words(file_path):
    try:
        with open(file_path) as file_object:
            contents = file_object.read()
    except FileNotFoundError:
        pass
    else:
        #计算该文件包含多少个单词
        words = contents.split()
        num_words = len(words)
        print("The file "+" has about " + str(num_words) +" words.")

#调用函数
file_paths = ['txt\A.txt','txt\B.txt','txt\C.txt']
for file_path in file_paths:
    count_words(file_path)

当文件C.txt不存在时,还是执行,只时执行结果没有任何输出

pass语句还充当了占位符,它提醒你在程序的某个地方什么都没有做,并且以后也需要在这里做什么。

posted @ 2017-11-26 16:16  OLIVER_QIN  阅读(2214)  评论(0编辑  收藏  举报