ActiveState Code

Recipe 252530: Exception Handling in an Expression


I use the following function to do extremely quick-and-dirty exception handling in an expression, without having to use try/except.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def throws(f, *a, **k):
    "Return True if f(*a,**k) raises an exception."
    try:
        f(*a,**k)
    except:
        return True
    else:
        return False


# Example - get numbers from a file, ignoring ill-formatted ones.
data = [float(line) for line in open(some_file) if not throws(float, line)]

Discussion

Maybe "raises" would be a better name, but I use "throws" - too much C++ rattling around in my brain I guess.

Comments

  1. 1. At 2:57 a.m. on 15 dec 2003, Gregor Rayman said:

    extremely quick-and-dirty. Indeed quick and dirty ;-)

  2. 2. At 3:50 p.m. on 17 dec 2003, Scott David Daniels said:

    Slight improvement. Just slightly less dirty:

    def throws(exceptions, f, *a, **k):
        "Return True if f(*a,**k) raises these exceptions."
        try:
            f(*a,**k)
        except exceptions:
            return True
        return False
    

    You can then use

    throws(AttributeError, ...)
    

    or

    throws((NameError, KeyError), ...)
    

    To catch the exceptions you anticipate, while passing along those that you _should_ avoid (such as SystemExit). If you want a very broad exception class, use

    throws(Exception, ...)
    

    , which should cover all exceptions.

Sign in to comment