Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle specific exception type in python

Tags:

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

like image 376
Falmarri Avatar asked Dec 01 '10 21:12

Falmarri


People also ask

How can you catch a specific type of exception in Python?

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.

How do you handle specific exceptions?

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.


1 Answers

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") 
like image 57
mipadi Avatar answered Oct 11 '22 11:10

mipadi