Sep-15-2019, 10:11 PM
Hi all.
I have this simple code, which does pretty simple things as open a file within the class. But i cant decide what the best design. Is approach1 is better approach2? I need to understand when re-raise an exception and also is it better to catch FileNotFoundError in the class or in the main. What the best approach?
I have this simple code, which does pretty simple things as open a file within the class. But i cant decide what the best design. Is approach1 is better approach2? I need to understand when re-raise an exception and also is it better to catch FileNotFoundError in the class or in the main. What the best approach?
import json import sys class Approach2FileNotFoundException(Exception): pass class Approach1: def __init__(self, config): self.config = self._open(config) def _open(self, config): with open(config, "r") as fh: return json.load(fh) class Approach2: def __init__(self, config): self.config = self._open(config) def _open(self, config): try: with open(config, "r") as fh: return json.load(fh) except FileNotFoundError as err: raise Approach2FileNotFoundException(err) def main(): try: a1 = Approach1("./config.txt") except FileNotFoundError as err: print(err) sys.exit(1) try: a2 = Approach2("./config.txt") except Approach2FileNotFoundException as err: print(err) sys.exit(1) if __name__ == "__main__": main()Many thanks