0

A very noob question here regarding exception handling and why doing it using if else is a bad idea (if at all it is). As a practice I prefer using try catch blocks wherever possible and especially if I need a certain kind of exception to be handled explicitly. However, I recently came across a situation where I was left confused. I would appreciate if someone could please guide me here:

Say for example I have the below snippet:

op = subprocess.run(['./someCommand', 'andItsOptions'], cwd=self.INSTALLATION_PATH_TO_THE_COMMAND_BEING_RUN)

Now all I need to do is check if the someCommand ran or not. On the basis of that, I just need to terminate the program if the command did not run (no additional steps need to be taken to handle this error... just print a message an exit) else continue with the flow.

As per my understanding 2 of the many ways this check could possibly be done are:

def someFunction():
    op = subprocess.run(['./someCommand', 'andItsOptions'], cwd=self.INSTALLATION_PATH_TO_THE_COMMAND_BEING_RUN)
    if op.returncode == 0:
       self.logger.info('successfully executed the command')
    else:
       self.logger.error('error while executing the command, program exits with return code: {}'.format(op.returncode))
       return False 

or

def someFunction():
    try:
       op = subprocess.run(['./someCommand', 'andItsOptions'], cwd=self.INSTALLATION_PATH_TO_THE_COMMAND_BEING_RUN, check=True)
    except Exception as e:
       self.logger.error(e)

Now what I am trying to understand here is which of the above two approaches (especially given that nothing really needs to be done with the error code other than terminating the flow of the program and printing the error code itself) is a preferred one and why? Why is one better / worse than the other if at all that's the case.

qre0ct
  • 5,680
  • 10
  • 50
  • 86
  • Notice that if ./someCommand does not exist, `subprocess.run` will throw an exception even with `check=False`. Besides that, I think the answers to this question covers it: https://stackoverflow.com/questions/7604636/better-to-try-something-and-catch-the-exception-or-test-if-its-possible-first – Ture Pålsson Dec 06 '21 at 10:36
  • @TurePålsson sure. That's again good coding practice if I am comprehending it correctly which is general is true. However, I want to know, in the specific case above, `(especially given that nothing really needs to be done with the error code other than terminating the flow of the program and printing the error code itself)` would one be better/worse than the other? – qre0ct Dec 06 '21 at 10:59

0 Answers0