try and except and finally 示意圖

try and expect and finally 示意圖





#example try except
def read_data(filename):
    data=[]
    fh=None
    try:
        fh=open(filename,encoding="utf-8")
        #fh=codecs.open(filename, 'r', "utf-8")
        for line in fh:
            if line.strip():
                #strip-delete the space
                #if it still have character,then is true
                #otherwise is false
                data.append(line)
    except(IOError, OSError) as err:
        print(err)
        return []
    finally:
        if fh is not None:
            fh.close()
    return data

0 意見:

張貼留言