I have the below script:
import jtp_aux as aux
def logger_path(path_logger):
return aux.init_logger(path_logger)
def generic_function(a, b):
return a/b
def main():
logger = logger_path(r'log_scratch.log')
try:
print(generic_function(2, 'l'))
except Exception as e:
logger.error(e, exc_info=True)
if __name__ == "__main__":
main()
I would need to catch any error thrown by the code and save into a file so I can analyse it later. However, I've been told that this generic exception catching is a bad practice and that the exceptions should be caught one by one, like this:
def main():
logger = logger_path(r'log_scratch.log')
try:
print(generic_function(2, 'l'))
except ValueError:
# Do something
except ZeroDivisionError:
# Do something
However, I'm struggling to understand why is that considered best practice if an unexpected exception could make the program fail without saving the error into a log. Any help with this will be hugely appreciated.
raise e, causing no program behaviour change at all, apart from logging the exception. It's bad practice if you catch all errors even dough you only want to catch some. Say you're accessing a dict, but expect it to fail sometimes, so put it inside a try catch block. Then not checking for the specific exception could cause your program to ignore other, unrelated exceptions.raise eagain, then your program will stop. You're explicitly catching the exception to make your program not stop, even in the face of an error, right?