为什么没有显示ValueError

时间:2018-12-05 14:04:22

标签: python

所以基本上我的代码是:

def process_contacts(contacts_file):
    f = None
    sections = []
    ret_dic = {}
    try:
        f = open(contacts_file, 'r')
        content = f.readlines()
        for line in content:
            if "#" in line:
                continue
            line = line.rstrip("\n")
            sections = line.split(',')               # section = categories of information on origin file
            if sections[1] == '' or len(sections) != 4:
                raise ValueError('Invalid input file')
            if sections[3] in ret_dic:
                    if sections[1] not in ret_dic[sections[3]]:
                        ret_dic[sections[3]].append(sections[1])
            else:
                ret_dic[sections[3]] = [sections[1]]
    except IOError:
        print 'Cannot process due to an IO error'
    except ValueError:
        raise ValueError('Invalid input file')
    finally:
        if f != None:
            f.close()
        if sections != []:
            return ret_dic

我在加注ValueError时遇到问题。我需要将ValueError引发为错误,但是我的代码只是跳过了它,我不明白为什么,我在整个Internet上搜索了它,但是也许我不明白。 无论如何,我打开的csv文件是:

Avi,Levi,Kushnir 7,Jerusalem
Moshe,,Hamakabim 4,Tel Aviv
Michael,Cohen,Herzel 70
Eli,Cohen,Haroe 6,Jerusalem
Moti,Cohen,shalom 5,Tel Aviv

1 个答案:

答案 0 :(得分:0)

这是因为您的finally封锁。您在raiseValueError except,然后说“哦,没关系”,然后结束finally。如果遇到错误,finally块将总是运行。