Home > OS >  Functional difference in exception handling between consecutive except, nested try, tuple exception
Functional difference in exception handling between consecutive except, nested try, tuple exception

Time:04-27

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}')

CodePudding user response:

I think either of the first two options are fine.

Personally I find I think the first is easier to read for a short simple function although if my_func was larger and more complex with nesting then I would opt for the second option as it makes it clear where exactly where sycopg2.Error may be raised.

The wouldn't use the third option. If you want to catch multiple exceptions use this syntax:

except (RuntimeError, TypeError, NameError):
    pass
  • Related