3

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

kjago
  • 69
  • 3
  • My vote is #1, but that's just my opinion. In reality, use whatever works for you/your team. – Abion47 May 10 '20 at 06:36
  • I see 1 and 2 most often. I rarely see the `try/else` syntax used. I only see 4 in the case of wanting to do unique things based on each error - even then `dictionary dispatch` often works well. What is most important is to just pick a convention and stick to it. – modesitt May 10 '20 at 06:38
  • For #1, you may want to just use [multiple excepts](https://stackoverflow.com/questions/6095717/python-one-try-multiple-except) instead – Moon Cheesez May 10 '20 at 06:44
  • 3
    All 4 of these do entirely different things. They are not about best, they are about what needs to be done *for a specific problem*. – MisterMiyagi May 10 '20 at 07:52

0 Answers0