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.