Python try/except - best practices / optimisation

Viewed 105

I'm looking for some information about best practices for try/except block in Python. I've meet few different approaches but I cannot find any proves/docs that one of them is the best to use.

Which one has the best performance and why?

  1. All i one
def get_information():
    try:
        foo = some_func(1)  # may raise KeyError
        bar = some_func(2)  # may raise ValueError
        return foo + baar
    except (KeyError, ValueError):
        logger.info('Lala')
        raise
  1. try/except without else
def get_information():
    try:
        foo = some_func(1)  # may raise KeyError
        bar = some_func(2)  # may raise ValueError
    except (KeyError, ValueError):
        logger.info('Lala')
        raise
    return foo + bar
  1. try/except with else
def get_information():
    try:
        foo = some_func(1)  # may raise KeyError
        bar = some_func(2)  # may raise ValueError
    except (KeyError, ValueError):
        logger.info('Lala')
        raise
    else:
        return foo + bar
  1. Separate all
def get_information():
    try:
        foo = some_func(1)  # may raise KeyError
    except KeyError:
        logger.info('KeyError')
        raise

    try:
        bar = some_func(2)  # may raise ValueError
    except ValueError:
        logger.info('ValueError')
        raise

    return foo + bar

Thank you

0 Answers
Related