Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch an exception in python and get a reference to the exception, WITHOUT knowing the type?

Tags:

I'm wondering how I can catch any raised object (i.e. a type that does not extend Exception), and still get a reference to it.

I came across the desire to do this when using Jython. When calling a Java method, if that method raises an exception, it will not extend Python's Exception class, so a block like this will not catch it:

try:     # some call to a java lib that raises an exception here except Exception, e:     # will never be entered 

I can do this, but then I have no access to the exception object that was raised.

try:     # some call to a java lib that raises an exception here except:     # will enter here, but there's no reference to the exception that was raised 

I can solve this by importing the Java exception type and catching it explicitly, but this makes it difficult/impossible to write generic exception handling wrappers/decorators.

Is there a way to catch some arbitrary exception and still get a reference to it in the except block?

I should note that I'm hoping for the exception handling decorator I am making to be usable with Python projects, not just with Jython projects. I'd like to avoid importing java.lang.Exception because that just makes it Jython-only. For example, I figure I can do something like this (but I haven't tried it), but I'd like to avoid it if I can.

try:     # some function that may be running jython and may raise a java exception except (Exception, java.lang.Exception), e:     # I imagine this would work, but it makes the code jython-only 
like image 762
TM. Avatar asked Jan 11 '10 23:01

TM.


2 Answers

You can reference exceptions using the sys module. sys.exc_info is a tuple of the type, the instance and the traceback.

import sys  try:     # some call to a java lib that raises an exception here except:     instance = sys.exc_info()[1] 
like image 67
Brian McKenna Avatar answered Oct 14 '22 05:10

Brian McKenna


FWIW, I have found that if you add this import to your Jython script:

from java.lang import Exception 

and just use the conventional Python Exception handler:

except Exception, e: 

it will catch both Python exceptions and Java exceptions

like image 25
Adrian Mehlig Avatar answered Oct 14 '22 05:10

Adrian Mehlig