Question

I try to construct a except clause that catches everything except [sic] a particular type of exception:

try:
    try:
        asdjaslk
    except not NameError as ne: #I want this block to catch everything except NameError
        print("!NameError- {0}: {1}".format(ne.__class__, ne))
except Exception as e: #NameError is the only one that should get here
    print("Exception- {0}: {1}".format(e.__class__, e))

The language accepts the not in the except clause, but does nothing with it:

>>> Exception- <type 'exceptions.NameError'>: name 'asdjaslk' is not defined

Is it possible to do this or should I reraise them?

Was it helpful?

Solution

You'll have to re-raise. An except statement can only whitelist, not blacklist.

try:
    asdjaslk
except Exception as ne:
    if isinstance(ne, NameError):
        raise

The not NameError expression returns False, so you are essentially trying to catch:

except False:

but no exception will ever match a boolean instance.

The syntax allows for any valid Python expression, and the thrown exception is matched against the outcome of that expression. except SomeException if debug else SomeOtherException: is perfectly valid, for example.

OTHER TIPS

You can can try this:

try:
    # your code raising exceptions

except NameError:
    # catch the exception you don't want to catch
    # but immediately raise it again:
    print("re-raising NameError- {0}: {1}".format(ne.__class__, ne))
    raise

except Exception as e:
    # handle all other exceptions here
    print("catching Exception- {0}: {1}".format(e.__class__, e))
    pass
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top