简体   繁体   中英

Proper way to handle file open and file close Exception

Please see this implementation:

@staticmethod
    def read_json_file__(file):
        reports = []
        try:
            with open(file) as json_file:
                data = json.load(json_file)
                for d in data:
                    # Do my stuff...
            try:
                json_file.close()
            except IOError as ex:
                raise Exception(ex)
            return reports
        except FileNotFoundError as ex:
            raise Exception('File \'{f}\' does not exist.'.format(f=ex.filename))
        except Exception:
            raise

I try to find the way to handle Exceptions so I handle file open Exception ( FileNotFoundError ) and file close Exception ( IOError ) and also add Generic Exception and raise it to caller method. Is this correct way to handle Exception ?

当使用with open(file) as json_file ,你不需要关闭,但如果你使用json_file = open(file)你需要关闭它(使用json_file.close() )。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM