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
Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.
The order of catch statements is important. Put catch blocks targeted to specific exceptions before a general exception catch block or the compiler might issue an error. The proper catch block is determined by matching the type of the exception to the name of the exception specified in the catch block.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With