Welcome, guest | Sign In | My Account | Store | Cart

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

Python, 12 lines
 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)]

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

2 comments

Gregor Rayman 20 years, 3 months ago  # | flag

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

Scott David Daniels 20 years, 3 months ago  # | flag

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.

Created by Chris Perkins on Sat, 13 Dec 2003 (PSF)
Python recipes (4591)
Chris Perkins's recipes (5)

Required Modules

  • (none specified)

Other Information and Tasks