Python: Catching specific exception

in except ValueError,e, e is an instance of the exception, not a string. So when you test if e is not equal to a particular string, that test is always False. Try:

if str(e) != "..."

instead.

Example:

def catch(msg):
    try:
        raise ValueError(msg)
    except ValueError as e:  # as e syntax added in ~python2.5
        if str(e) != "foo":
            raise
        else:
            print("caught!")

catch("foo")
catch("bar")

Typically, you don’t really want to rely on the error message if you can help it — It’s a little too fragile. If you have control over the callable macdat, instead of raising a ValueError in macdat, you could raise a custom exception which inherits from ValueError:

class MyValueError(ValueError): pass

Then you can only catch MyValueError and let other ValueErrors continue on their way to be caught by something else (or not). Simple except ValueError will still catch this type of exception as well so it should behave the same in other code which might also be catching ValueErrors from this function.

Leave a Comment