Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to catch an exception in python and get a reference to the exception, WITHOUT knowing the type?
    text
    copied!<p>I'm wondering how I can catch <strong>any</strong> raised object (i.e. a type that does not extend <code>Exception</code>), and still get a reference to it.</p> <p>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 <code>Exception</code> class, so a block like this will not catch it:</p> <pre><code>try: # some call to a java lib that raises an exception here except Exception, e: # will never be entered </code></pre> <p>I can do this, but then I have no access to the exception object that was raised.</p> <pre><code>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 </code></pre> <p>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.</p> <p>Is there a way to catch some arbitrary exception and still get a reference to it in the <code>except</code> block?</p> <p><strong>I should note</strong> 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 <code>java.lang.Exception</code> 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.</p> <pre><code>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 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload