Handle specific exception type in python

31,551

Solution 1

Well, really, you probably should keep the handler for KeyboardInterrupt separated. Why would you only want to handle keyboard interrupts in debug mode, but swallow them otherwise?

That said, you can use isinstance to check the type of an object:

try:
    stuff()
except Exception as e:
    if _debug and isinstance(e, KeyboardInterrupt):
        sys.exit()
    logger.exception("Normal handling")

Solution 2

This is pretty much the way it's done.

try:
    stuff()
except KeyboardInterrupt:
    if _debug:
        sys.exit()
    logging.exception("Normal handling")
except Exception as e:
    logging.exception("Normal handling")

There's minimal repetition. Not zero, however, but minimal.

If the "normal handling" is more than one line of code, you can define a function to avoid repetition of the two lines of code.

Solution 3

You should let KeyboardInterrupt bubble all the way up and trap it at the highest level.

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        sys.exit()
    except:
        pass

def main():
    try:
        stuff()
    except Exception as e:
        logging.exception("Normal handling")
        if _debug:
            raise e

Solution 4

Either use the standard method mentioned in the other answers, or if you really want to test within the except block then you can use isinstance().

try:
    stuff()
except Exception as e:
   if _debug and isinstance(e, KeyboardInterrupt):
        sys.exit()
    logging.exception("Normal handling")
Share:
31,551

Related videos on Youtube

Falmarri
Author by

Falmarri

Updated on July 09, 2022

Comments

  • Falmarri
    Falmarri almost 2 years

    I have some code that handles an exception, and I want to do something specific only if it's a specific exception, and only in debug mode. So for example:

    try:
        stuff()
    except Exception as e:
        if _debug and e is KeyboardInterrupt:
            sys.exit()
        logging.exception("Normal handling")
    

    As such, I don't want to just add a:

    except KeyboardInterrupt:
        sys.exit()
    

    because I'm trying to keep the difference in this debug code minimal

  • Velociraptors
    Velociraptors over 13 years
    You beat me by 30 seconds, I think
  • Falmarri
    Falmarri over 13 years
    This is on an embedded system running without a shell. So we could only possibly get a keyboard interrupt in debug mode. So we just handle all exceptions.
  • mipadi
    mipadi over 13 years
    @marcog: except Exception as e is valid in Python 2.6+.
  • Paulo Scardine
    Paulo Scardine over 13 years
    -1: 'else' should be 'except', 'else' clause is for code to be executed if there is no exception.
  • Lex
    Lex over 13 years
    Yes, 'else' branch will be executed when there is no exception. It's just for example. But you are right I should edit code example to show 'real' program state.