0

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 ?

Dan Raz
  • 5
  • 4
  • 3
    Handling exceptions by raising a less specific or even the same exception without doing any handling is usually not very helpful. – Klaus D. Nov 21 '20 at 06:41
  • There is no benefit in handling the exceptions the way you do, as explained by @KlausD. And no need to close the file when using `with` context manager. And on more general level - there is also `finally` block of the `try/except/else/finally` that will be executed always at the end. – buran Nov 21 '20 at 06:58

1 Answers1

0

When using with open(file) as json_file, you do not need to close, but if you use json_file = open(file) you do need to close it (with json_file.close()).

KetZoomer
  • 2,701
  • 3
  • 15
  • 43