Is there a functional difference between the exception handling in code blocks 1,2,3? I want to print different messages based on the type error for example including the error code if psycopg2 error. I have read that nested try except blocks are good practice. I'm using psycopg2 as an example.
# code block 1
def my_func(fun_arg):
try:
# ... some stuff
except psycopg2.Error as error:
print(f"Error while inserting data to PostgreSQL {type(error).__name__} {error.pgcode} {error.pgerror}")
except Exception as error:
print(f'error in my_func {type(error).__name__} {error.args}')
# code block 2
def my_func(fun_arg):
try:
# ... some stuff
try:
# ... some stuff
except psycopg2.Error as error:
print(f"Error while inserting data to PostgreSQL {type(error).__name__} {error.pgcode} {error.pgerror}")
except Exception as error:
print(f'error in my_func {type(error).__name__} {error.args}')
# code block 3
def my_func(fun_arg):
try:
# ... some stuff
except (psycopg2.Error, Exception) as error:
if (type(error).__name__ in (
'DatabaseError', 'OperationalError', 'NotSupportedError',
'ProgrammingError', 'DataError','IntegrityError',))
print(f"Error while inserting data to PostgreSQL {type(error).__name__} {error.pgcode} {error.pgerror}")
else:
print(f'error in my_func {type(error).__name__} {error.args}')